滑块实现效果

效果:
在这里插入图片描述
代码:

<!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>
  <script src="https://cdn.staticfile.org/jquery/3.6.0/jquery.min.js"></script>

  <style>
    * {
      padding: 0;
      margin: 0;
    }

    .boxBar {
      padding: 10px 0;
      margin: 15px;
      width: 200px;
    }

    .bar {
      height: 6px;
      background-color: #ccc;
      position: relative;
      cursor: pointer;
    }

    .slideBlock {
      height: 16px;
      width: 10px;
      background-color: blue;
      position: absolute;
      top: -5px;
      left: 20px;
      z-index: 10;
      border-radius: 3px;
      cursor: pointer;
    }

    .track {
      height: 5px;
      width: 20px;
      background-color: blue;
      position: absolute;
      top: 0;
      left: 0;
    }

    .text {
      color: blue;
      margin-top: 20px;
    }
  </style>
</head>

<body>

  <div class="boxBar">
    <div class="bar">
      <div class="slideBlock"></div>
      <div class="track"></div>
    </div>
    <p class="text">20%</p>
  </div>

  <script>

    $('.slideBlock').mousedown(function (e) {

      $('.boxBar').mousemove(function (ev) {

        console.log(ev.clientX, this.offsetLeft, 'mousemove');
        let left = ev.clientX - this.offsetLeft
        let w = $('.bar').width()

        if (left > w) left = w
        if (left < 0) left = 0
        $('.slideBlock').css({ 'left': left + 'px' })
        $('.track').css({ 'width': left + 'px' })

        $('.text').text(Math.ceil(left / w * 100) + '%')
      })
      document.onmouseup = function () {
        $('.boxBar').off('mousemove')
      }
    })

    // 鼠标点击轨道改变
    $('.bar').click(function (ev) {
      console.log(ev.clientX, this.offsetLeft);
      let left = ev.clientX - this.offsetLeft
      $('.slideBlock').css({ 'left': left + 'px' })
      $('.track').css({ 'width': left + 'px' })
      console.log(this.offsetLeft, '899');
      let w = $('.bar').width()
      $('.text').text(Math.ceil(left / w * 100) + '%')
    })
  </script>
</body>

</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值