可拖动元素卡在边缘附近

时间:2019-03-12 17:19:51

标签: javascript

拖动元素似乎使其在接触其父容器的边缘之前被随机卡住。有人能够发现为什么会这样吗?

另一方面,我无法将记住的位置正确地转移到“ updateDrag”。

不,我不需要任何jQuery解决方案,例如使用jQuery UI创建的解决方案。

let $container = document.getElementById('container');
let $element = document.getElementById('element');
let mousePosition;
let offset = [0, 0];
let isDown = false;

function initDrag(event) {
  isDown = true;
  // Element also remembers previous position wrong
  // offset = [
  //     $element.offsetLeft - event.clientX,
  //     $element.offsetTop - event.clientY
  // ];
  offset = [
    0,
    0
  ];
}

function updateDrag(event) {
  event.preventDefault();
  if (isDown) {
    mousePosition = {
      x: event.clientX,
      y: event.clientY
    };
    let diffY = mousePosition.y - offset[1];
    let diffX = mousePosition.x - offset[0];

    if (diffY >= 0 && diffY + $element.offsetHeight <= $container.offsetHeight) {
      $element.style.top = (mousePosition.y + offset[1]) + 'px';
    }
    if (diffX >= 0 && diffX + $element.offsetWidth <= $container.offsetWidth) {
      $element.style.left = (mousePosition.x + offset[0]) + 'px';
    }
  }
}

function haltDrag() {
  isDown = false;
}

$element.addEventListener('mousedown', initDrag, false);
document.addEventListener('mouseup', haltDrag, false);
document.addEventListener('mousemove', updateDrag, false);
#container {
  position: relative;
  top: 10px;
  left: 10px;
  height: 300px;
  width: 300px;
  background-color: green;
}

#element {
  position: absolute;
  left: 0;
  top: 0;
  width: 100px;
  height: 100px;
  background: red;
  color: blue;
}
<div id="container">
  <div id="element"></div>
</div>

0 个答案:

没有答案