原生js 进度条

个人实际开发中用到的效果问题总结出来便于自己以后开发查看调用,如果也适用其他人请随意拿走勿喷就行!

进度条这一效果还是比较简单的,并没有什么难度,代码还简单好理解,它是由一个滑块控制进度条的快进,并计算进度的百分比给展示出来,具体效果如下。

HTML代码

<div class="box">
    <p class="p">0%</p>
    <div class="con"></div>
    <span class="span"></span>
 </div>

CSS代码

<style>
    *{
      margin: 0;
      padding: 0;
    }
    .box{
      width: 1000px;
      height: 100px;
      margin: 50px auto;
      position: relative;
    }
    .con{
      width: 0;
      height: 10px;
      background: red;
    }
    .span{
      width: 100px;
      height: 50px;
      background: skyblue;
      display: block;
      position: absolute;
      top: 40px;
      left: 0;
    }
    .p{
      width: 100%;
      height: 20px;
      text-align: center;
    }
  </style>

JS代码

(win=>{
    const oBox = document.getElementsByClassName('box')[0];
    const oCon = document.getElementsByClassName('con')[0];
    const oSpan = document.getElementsByClassName('span')[0];
    const oP = document.getElementsByClassName('p')[0];
    var content_X = (oBox.offsetWidth - oSpan.offsetWidth) / 100;
    oSpan.onmousedown = function(ev){
      var disX_1 = ev.clientX;
      var off_X = this.offsetLeft;
      document.onmousemove = function(ev){
        var disX_2 = ev.clientX - disX_1;
        var x = disX_2 + off_X;
        if(x <= 0){
          x = 0;
        }
        if(x >= (oBox.offsetWidth - oSpan.offsetWidth)){
          x = oBox.offsetWidth - oSpan.offsetWidth;
        }
        oP.innerHTML = parseInt(x / content_X) + '%';
        oSpan.style.left = x + 'px';
        oCon.style.width = x * oBox.offsetWidth / (oBox.offsetWidth - oSpan.offsetWidth) + 'px';
      }
      document.onmouseup = function(){
        document.onmousemove = null;
        document.onmouseup = null;
      }
    }
  })(window)

 

posted @ 2020-05-20 15:02  迷小落  阅读(455)  评论(0编辑  收藏  举报