JavaScript帶有百分比的滑動條效果

antzone發表於2017-05-15

分享一段程式碼例項,它實現了帶有百分比的滑動調效果,在實際應用中還是比較美觀的。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼執行程式碼
<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<title>原生js實現可拖拽進度條效果</title>
<style>
.scale_panel {
  margin-top: 50px;
  width: 600px;
  position: relative;
  line-height: 18px;
  left: 60px;
  top: -0px;
}
.scale .jindu_btn {
  position: absolute;
  left: -10px;
  top: 10px;
  height: 18px;
  width: 18px;
  background-color: #00ffff;
  border-radius: 20px;
  margin-top: -18px;
  cursor: pointer;
}
.jindu_btn span {
  font-size: 16px;
  position: absolute;
  top: -20px;
  left: 0px;
}
.scale {
  background-repeat: repeat-x;
  background-position: 0 100%;
  background-color: #efefef;
  width: 600px;
  height: 5px;
  position: relative;
  font-size: 0px;
  border-radius: 3px;
}
.scale div {
  background-repeat: repeat-x;
  background-color: #00ffff;
  width: 0px;
  position: absolute;
  height: 5px;
  width: 0;
  left: 0;
  bottom: 0;
  border-radius: 3px;
}
</style>
</head>
<body>
  <div class="scale_panel">
    <div class="scale" id="bar">
      <div id="jingxing"></div>
      <div class="jindu_btn" id="btn">
        <span id="title">0%</span>
      </div>
    </div>
  </div>
  <script>
    var scale = function (btn, bar, title) {
      this.btn = document.getElementById(btn);
      this.bar = document.getElementById(bar);
      this.title = document.getElementById(title);
      this.step = this.bar.getElementsByTagName("div")[0];
      this.init();
    };
    scale.prototype = {
      init: function () {
        var f = this,
          g = document,
          b = window,
          m = Math;
        f.btn.onmousedown = function (e) {
          var x = (e || b.event).clientX;
          var l = this.offsetLeft;
          var max = f.bar.offsetWidth - this.offsetWidth;
          g.onmousemove = function (e) {
            var thisX = (e || b.event).clientX;
            var to = m.min(max, m.max(-2, l + (thisX - x)));
            f.btn.style.left = to + 'px';
            f.ondrag(m.round(m.max(0, to / max) * 100), to);
            b.getSelection ? b.getSelection().removeAllRanges() : g.selection.empty();
          };
          g.onmouseup = new Function('this.onmousemove=null');
        };
      },
      ondrag: function (pos, x) {
        this.step.style.width = Math.max(0, x) + 'px';
        this.title.innerHTML = pos + '%';
      }
    }
    new scale('btn', 'bar', 'title');
  </script>
</body>
</html>

相關文章