JS滑动条

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

JS滑动条

setTimeout()   2022-09-27 我要评论

在完成这个案例之前需要看一下这个博客:JS案例-添加缓动画

这个案例会用到上面博客的缓动画函数。实现效果如下:

完整代码如下:

html代码:

<!DOCTYPE html>
<html lang="en">
 
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
 
    <title>滑动条案例</title>
    <style>
        body {
            overflow-x: hidden;
        }
        
        .slidebar {
            position: absolute;
            top: 500px;
            right: 0;
            width: 40px;
            height: 40px;
            text-align: center;
            line-height: 40px;
            cursor: pointer;
            color: #fff;
            background-color: #891383;
        }
        
        .con {
            position: absolute;
            left: 0;
            top: 0;
            width: 200px;
            height: 40px;
            background-color: #891383;
            color: #fff;
            text-align: center;
            line-height: 40px;
            z-index: -1;
        }
    </style>
    <script src="../js/index.js"></script>
</head>
 
<body>
    <div class="slidebar">
        <span>⬅</span>
        <div class="con">问题反馈</div>
    </div>
    <script>
        // 获取元素
        var slide = document.querySelector('.slidebar')
        var span = document.querySelector('span');
        var con = document.querySelector('.con');
        slide.addEventListener('mouseenter', function() {
            // 当动画执行完毕就把左箭头改为右箭头
            moves(con, -160, function() {
                slide.children[0].innerHTML = '➡'
            })
        });
        slide.addEventListener('mouseleave', function() {
            // 当动画执行完毕就把右箭头又变为左箭头
            moves(con, 0, function() {
                slide.children[0].innerHTML = '⬅'
            })
        })
    </script>
</body>
 
</html>

JS代码:

function moves(obj, target, callback) {
    clearInterval(obj.timer);
    obj.timer = setInterval(function() {
        // 把步长值改为整数,不要出现小数的情况 往上取整
        var step = (target - obj.offsetLeft) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step);
        // 回调函数写在清除定时器里面 这里只能写等于
        if (obj.offsetLeft == target) {
            clearInterval(obj.timer);
            if (callback) {
                callback();
            }
        }
        obj.style.left = obj.offsetLeft + step + 'px';
        // console.log(obj.style.left);
 
    }, 15);
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们