美文网首页
鼠标拖拽

鼠标拖拽

作者: codeffee | 来源:发表于2017-03-18 18:12 被阅读0次
    var item1=document.querySelector(".item1");
    
    item1.onmousedown=function (e){
        var dx=e.pageX-this.offsetLeft;
        //计算出鼠标按下的位置距离元素的左边的距离
        var dy=e.pageY-this.offsetTop;
        //计算出鼠标按下的位置距离元素的顶部的距离
        document.onmousemove=function(e){
          var l=e.pageX-dx;
          /*元素的left定位值和top定位值都是基于左上角,但是left和top值我们需要通
          过鼠标的位置减掉鼠标距离元素左边的距离,这样才能保证我们鼠标点击的位置  
          不变*/
          var t=e.pageY-dy;
          item1.style.left=l+'px';
          item1.style.top=t+'px';
        }
    
        document.onmouseup=function (e){
          this.onmouseup=this.onmousemove=null;
        }
        return false
    }
    

    相关文章

      网友评论

          本文标题:鼠标拖拽

          本文链接:https://www.haomeiwen.com/subject/pfqpnttx.html