Rumah  >  Artikel  >  hujung hadapan web  >  利用Jquery实现可拖动进度条的效果

利用Jquery实现可拖动进度条的效果

PHP中文网
PHP中文网asal
2017-06-22 15:03:262872semak imbas

这篇文章主要介绍了jQuery实现可拖动进度条实例代码,非常不错,具有参考借鉴价值,需要的朋友可以参考下

html

 <div class="progress">
 <div class="progress_bg">
  <div class="progress_bar"></div>
 </div>
 <div class="progress_btn"></div>
 <div class="text">0%</div>
</div>

css

.progress{position: relative; width:300px;margin:100px auto;}
.progress_bg{height: 10px; border: 1px solid #ddd; border-radius: 5px; overflow: hidden;background-color:#f2f2f2;}
.progress_bar{background: #5FB878; width: 0; height: 10px; border-radius: 5px;}
.progress_btn{width: 20px; height: 20px; border-radius: 5px; position: absolute;background:#fff; 
left: 0px; margin-left: -10px; top:-5px; cursor: pointer;border:1px #ddd solid;box-sizing:border-box;}
.progress_btn:hover{border-color:#F7B824;}

js

   $(function(){
    var tag = false,ox = 0,left = 0,bgleft = 0;
    $(&#39;.progress_btn&#39;).mousedown(function(e) {
     ox = e.pageX - left;
     tag = true;
    });
    $(document).mouseup(function() {
     tag = false;
    });
    $(&#39;.progress&#39;).mousemove(function(e) {//鼠标移动
     if (tag) {
      left = e.pageX - ox;
      if (left <= 0) {
       left = 0;
      }else if (left > 300) {
       left = 300;
      }
      $(&#39;.progress_btn&#39;).css(&#39;left&#39;, left);
      $(&#39;.progress_bar&#39;).width(left);
      $(&#39;.text&#39;).html(parseInt((left/300)*100) + &#39;%&#39;);
     }
    });
    $(&#39;.progress_bg&#39;).click(function(e) {//鼠标点击
     if (!tag) {
      bgleft = $(&#39;.progress_bg&#39;).offset().left;
      left = e.pageX - bgleft;
      if (left <= 0) {
       left = 0;
      }else if (left > 300) {
       left = 300;
      }
      $(&#39;.progress_btn&#39;).css(&#39;left&#39;, left);
      $(&#39;.progress_bar&#39;).animate({width:left},300);
      $(&#39;.text&#39;).html(parseInt((left/300)*100) + &#39;%&#39;);
     }
    });
   });

效果图

实现原理

  首先是用mousedown()鼠标按下事件保存一个状态值,mouseup()鼠标抬起事件取消该状态,再同时配合mousemove()鼠标移动事件,实现按住拖动的效果。

在鼠标移动的同时去改变精度条的长度和按钮的相对左部的距离。

  然后就是距离的计算,主要利用的就是pageX() 属性。pageX是鼠标指针相对于文档的左边缘的位置。在鼠标按下是就记录相对位置,在鼠标移动后就可求出鼠标移动的距离。从而改变按钮位置和进度条长度。

Atas ialah kandungan terperinci 利用Jquery实现可拖动进度条的效果. Untuk maklumat lanjut, sila ikut artikel berkaitan lain di laman web China PHP!

Kenyataan:
Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn