js拖動框

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    *{
      padding: 0px;
      margin: 0px;
    }
    .box{
      width: 300px;
      height: 30px;
      background: pink;
      position: absolute;
      left: 0;
      top: 0;
    }
    .box:hover{
      cursor: move;
    }
  </style>
</head>
<body>
  <div class="box" id="moveElement">我可以移動</div>
  <script>
    window.onload = function(){
      // 獲取元素節(jié)點(diǎn)
      let moveElement = document.getElementById('moveElement');
      // 給元素注冊鼠標(biāo)按下事件
      moveElement.onmousedown = function(e){
        //兼容  e || window.event  現(xiàn)在都可以
        let event = e || window.event;  
        // 獲取鼠標(biāo)按下去的那一個點(diǎn)距離邊框頂部和左側(cè)的距離
        let point_x=event.offsetX;
        let point_y=event.offsetY;
        //  鼠標(biāo)移動(小方塊在文檔上移動,給文檔注冊一個是移動事件)
        document.onmousemove = function(ent){
          let evt = ent || window.event;
          // 獲取鼠標(biāo)移動的坐標(biāo)位置
          let ele_left= evt.clientX - point_x;
          let ele_top= evt.clientY - point_y;

          // ----冗余代碼---
          // if(ele_left<=0){
          //   // 設(shè)置水平方向的最小值
          //   ele_left = 0
          // }else if(ele_left >= window.innerWidth - moveElement.offsetWidth){
          //   // 設(shè)置水平方向的最大值
          //   ele_left = window.innerWidth - moveElement.offsetWidth
          // }
          // if(ele_top<=0){
          //   // 設(shè)置垂直方向的最小值
          //   ele_top = 0
          // }else if(ele_top >= window.innerHeight - moveElement.offsetHeight){
          //   // 設(shè)置垂直方向的最大值
          //   ele_top = window.innerHeight - moveElement.offsetHeight
          // }
          // 優(yōu)化為下面的
          ele_left = Math.min(Math.max(0,ele_left), window.innerWidth - moveElement.offsetWidth)
          ele_top=  Math.min(Math.max(0,ele_top),  window.innerHeight - moveElement.offsetHeight)
          
          moveElement.style.left = ele_left + 'px';
          moveElement.style.top = ele_top + 'px'
        }

        // 抬起停止移動
        document.onmouseup = function(event){
          console.log("抬起停止移動" )
          // 移除移動和抬起事件
          this.onmouseup = null;
          this.onmousemove = null;
          //修復(fù)低版本的ie可能出現(xiàn)的bug
          if(typeof moveElement.releaseCapture!='undefined'){  
            moveElement.releaseCapture();  
          }  
        }
        // 解決有些時候,在鼠標(biāo)松開的時候,元素仍然可以拖動-使用的是第二種方式
        document.ondragstart = function(ev) {
          ev.preventDefault();
        }
        document.ondragend = function(ev) {
          ev.preventDefault();
        }
      }
    }
  </script>
</body>
</html>

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容