JS实现滑动条案例

 更新时间:2022年07月05日 07:28:21   作者:setTimeout()  
这篇文章主要为大家详细介绍了JS实现滑动条案例,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了JS实现滑动条效果的具体代码,供大家参考,具体内容如下

在完成这个案例之前需要看一下这个博客: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);
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

最新评论