js实现手动滑动条

效果如下图所示:

滑动效果如下图:

 

样例页面代码如下:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title>test</title>
    <style>
    #bg_bar {
        margin: 10px;
        height: 80px;
        border-radius: 38px;
        background-color: gray;
        opacity: 0.5;
    }

    #touch_bar {
        position: relative;
        top: -82px;
        border: 2px solid blue;
        width: 15%;
        height: 80px;
        border-radius: 38px;
        background-color: white;
        display: flex;
        flex: row;
        justify-content: center;
        align-items: center;
        z-index: 20;
    }

    #bg_new {
        position: relative;
        top: -164px;
        height: 80px;
        border-radius: 38px;
        background-color: blue;
        z-index: 15;
    }

    #bg_old {
        height: 80px;
        z-index: 10;
        display: flex;
        flex: row;
        justify-content: center;
        align-items: center;
    }
    </style>
</head>

<body>
    <div id="bg_bar">
        <div id="bg_old">
            <span style="font-size: 30px">滑动登录</span>
        </div>
        <div id="touch_bar">
        </div>
        <div id="bg_new"></div>
    </div>
</body>
<script>
var isTouch = false; //标志位,是否点击
var startX = 0; //鼠标点击的偏移量,实现平滑移动的保证
(function() {
    var touch_bar = document.getElementById("touch_bar");
    var bg_bar = document.getElementById("bg_bar");
    var bg_new = document.getElementById("bg_new");
    /* 
    为滑块绑定鼠标移动事件
    当鼠标在滑块上移动时,使滑块在水平方向上跟随移动
    是否移动要根据标志位检测滑块是否被点击
    */
    touch_bar.onmousemove = function(ev) {
        var ev = ev || event;
        // console.log(ev.clientX);
        if (ev.clientX - startX > 0 &&
            ev.clientX - startX < bg_bar.offsetWidth - touch_bar.offsetWidth &&
            isTouch) {
            touch_bar.style.left = ev.clientX - startX + "px";
            bg_new.style.width = ev.clientX - startX + touch_bar.offsetWidth / 2 + "px";
        }
    }
    /*
    设置滑块点击事件,改变标志位,并重置偏移量
    */
    touch_bar.onmousedown = function(ev) {
        isTouch = true;
        startX = event.clientX;
    }
    /*
    设置滑块鼠标点击取消事件,改变标志位,重置偏移量
    */
    touch_bar.onmouseup = function(ev) {
        isTouch = false;
        startX = 0;
        touch_bar.style.left = "0px";
        bg_new.style.width = "0px";
    }
    /*
    设置滑块鼠标移出事件,改变标志位,并重置偏移量
    */
    touch_bar.onmouseout = function(ev) {
        isTouch = false;
        startX = 0;
        touch_bar.style.left = "0px";
        bg_new.style.width = "0px";
    }

    //重置偏移量
    touch_bar.style.left = "0px";
    bg_new.style.width = "0px";
})();
</script>

</html>

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值