js實現拖動效果


實現這個功能主要是配合鼠標的mouse事件,拖動原理如下圖(以橫向x坐標為例,y軸原理是一樣的):

html代碼:

 <div id="box"></div>

CSS代碼:

#box {
      position: absolute;
      width: 100px;
      height: 100px;
      top: 10px;
      left: 10px;
      background: red;
}

javaScript代碼:

 let box = document.getElementById('box');
    document.onmousedown = function (e) {
      let disx = e.pageX - box.offsetLeft;
      let disy = e.pageY - box.offsetTop;
      document.onmousemove = function (e) {
        box.style.left = e.pageX - disx + 'px';
        box.style.top = e.pageY - disy + 'px';
      }
    //釋放鼠標按鈕,將事件清空,否則始終會跟着鼠標移動
      document.onmouseup = function () {
        document.onmousemove = document.onmouseup = null;
      }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM