原生js一个简单的拖动

style如下

#div1{
  width: 200px;
  height: 20px;
  background: red;
  position: relative;
  margin-top:200px;
  margin-left:auto;
  margin-right:auto;
}
#div2{
  width: 20px;
  height: 20px;
  background: blue;
  position: absolute;
  left: 0px;
  top:0px;
}

 

html如下

<div id="div1">
    <div id="div2"></div>
</div>

<p id="con"></p>

 

js如下

    window.onload = function(){
        div2.onmousedown = function(ev){
            var e = ev || event;
            var disX = e.clientX - this.offsetLeft;

            document.onmousemove = function(ev){
                var e = ev || event;
                var t = e.clientX - disX;

                if( t <= 0  ) t = 0;

                if( t >= div1.clientWidth - div2.offsetWidth ){
                    t = div1.clientWidth - div2.offsetWidth;
                };

                var Scale = t / (div1.clientWidth - div2.offsetWidth);

                div2.style.left = t + "px";  

                con.innerHTML = t;
            };

            document.onmouseup = function (){
                document.onmousemove = null;
                document.onmouseup = null;  
            };
        }
    }

 

posted on 2018-06-06 13:54  婆婆买了只kitty  阅读(85)  评论(0编辑  收藏  举报

导航