1. 程式人生 > 程式設計 >js實現限定區域範圍拖拉拽效果

js實現限定區域範圍拖拉拽效果

本文例項為大家分享了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>

   #drag {

    background: aqua;
    width: 200px;
    height: 200px;
    position: absolute;
    -moz-user-select: none;
    -khtml-user-select: none;
    user-select: none;

   }

   #parent {
    position: relative;
    background: #cde4dc;
    height: 80vh;
    overflow: hidden;

   }

  </style>
 </head>

<body>
  <section id="parent">
   <div id="drag"><div>這是一個測試</div></div>
  </section>
  <script type="text/javascript">

   //自執行函式,需要拖拽的元素需要設定position:absolute,父元素position:relative
   //有傳父親節點、若無則預設body為父節點

   ((parent,children,mouseType) => {

    if (!children) return;
    let childrenDiv = document.querySelector(children);
    childrenDiv.style.position = 'absolute';
    let parentDiv = parent

     ? document.querySelector(parent)
     : document.querySelector('body');

    let isDown = false;

    let x,y,l,t = 0;

    childrenDiv.onmousedown = function (e) {

     x = e.clientX;
     y = e.clientY;

     // 獲取左部和底部的偏移量

     l = childrenDiv.offsetLeft;
     t = childrenDiv.offsetTop;
     isDown = true;
     childrenDiv.style.cursor = mouseType || 'move';

    };

    // 滑鼠移動

    window.onmousemove = function (e) {

     if (!isDown) {

      return;

     }

     //獲取移動後的x和y座標

     let nx = e.clientX;
     let ny = e.clientY;

     //獲取父元素的寬高

     let parentWidth = parentDiv.clientWidth;
     let parentHeight = parentDiv.clientHeight;

     //獲取子元素的寬高

     let childrenWidth = childrenDiv.clientWidth;
     let childrenHight = childrenDiv.clientHeight;

     // 計算移動後的左偏移量和頂部偏移量

     let nLeft = nx - (x - l);
     let nTop = ny - (y - t);
     let nRight = nLeft + childrenWidth;
     let nBottom = nTop + childrenHight;
     nLeft = nLeft <= 0 ? 0 : nLeft; //判斷左邊距離是否越界
     nTop = nTop <= 0 ? 0 : nTop; //判斷上邊距離是否越界
     //判斷右邊距離大於父元素寬度

     if (nRight >= parentWidth) {

      nLeft = parentWidth - childrenHight;

     }

     // 判斷下邊界是否越界

     if (nBottom >= parentHeight) nTop = parentHeight - childrenHight;
     childrenDiv.style.left = nLeft + 'px';
     childrenDiv.style.top = nTop + 'px';

    };

    // 滑鼠抬起事件
    document.onmouseup = function (e) {
     //滑鼠抬起
     isDown = false;

     childrenDiv.style.cursor = 'default';

    };

   })('#parent','#drag','move');

  </script>
 </body>
</html>

js實現限定區域範圍拖拉拽效果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。