如何實(shí)現(xiàn)鼠標(biāo)超出可視窗口仍然可以拖動(dòng)元素

一定要給documentElement 或者 onwerDocument 綁定鼠標(biāo)移動(dòng)事件,否則鼠標(biāo)脫離可視區(qū)域?qū)o(wú)法繼續(xù)拖動(dòng)元素

<!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>
    html,
    body {
      height: 100%;
      width: 100%;
      background: lightblue;
      padding: 0;
      margin: 0;
    }

    .mask {
      position: relative;
      width: 100%;
      height: 100%;
      background: rgba(1, 1, 1, 0.5);
      overflow: hidden;
    }

    .move {
      height: 200px;
      width: 300px;
      background: yellow;
      position: absolute;
      cursor: pointer;
      left: 100px;
      top: 100px;
      /* transform: translate(10px,20px); */
    }
  </style>
</head>

<body>
  <div class="mask">
    <div class="move"></div>
  </div>
</body>
<script>
  window.onload = function () {
    let move = document.getElementsByClassName('move')[0]
    let mask = document.getElementsByClassName('mask')[0]
    // let dom = move.ownerDocument
    let dom = document.documentElement
    let x //保存上一次的鼠標(biāo)位置
    let y //保存上一次的鼠標(biāo)位置
    let oldL //保存上一次鼠標(biāo)的位移
    let oldY //保存上一次鼠標(biāo)的位移
    let mousemove = function (e) {
      move.style.left = e.clientX - x + oldL + 'px'
      move.style.top = e.clientY - y + oldY + 'px'
    }
    let mousedownEv = function (e) {
      x = e.clientX
      y = e.clientY
      oldL = move.style.left ? parseInt(move.style.left) : parseInt(window.getComputedStyle(move).left) //第一次獲取不到css標(biāo)簽中的值
      oldY = move.style.top ? parseInt(move.style.top) : parseInt(window.getComputedStyle(move).top) //第一次獲取不到css標(biāo)簽中的值
      dom.addEventListener('pointermove', mousemove)
    }
    //綁定事件
    dom.addEventListener('mousedown', mousedownEv)
    dom.addEventListener('mouseup', function (e) {
      dom.removeEventListener('pointermove', mousemove)
      console.log('up')
    })
  }
</script>

</html>

代碼可能實(shí)現(xiàn)的有些不太靈活歡迎指出

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

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

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