如何实现鼠标超出可视窗口仍然可以拖动元素

一定要给documentElement 或者 onwerDocument 绑定鼠标移动事件,否则鼠标脱离可视区域将无法继续拖动元素

<!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 //保存上一次的鼠标位置
    let y //保存上一次的鼠标位置
    let oldL //保存上一次鼠标的位移
    let oldY //保存上一次鼠标的位移
    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标签中的值
      oldY = move.style.top ? parseInt(move.style.top) : parseInt(window.getComputedStyle(move).top) //第一次获取不到css标签中的值
      dom.addEventListener('pointermove', mousemove)
    }
    //绑定事件
    dom.addEventListener('mousedown', mousedownEv)
    dom.addEventListener('mouseup', function (e) {
      dom.removeEventListener('pointermove', mousemove)
      console.log('up')
    })
  }
</script>

</html>

代码可能实现的有些不太灵活欢迎指出

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容