JavaScript 实现鼠标拖动元素实例代码


当然,我可以为你提供一个简单的JavaScript实现鼠标拖动元素的示例代码。这个示例将使用纯JavaScript,不依赖任何外部库。


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Drag Element Example</title>
<style>
  #draggable {
    width: 100px;
    height: 100px;
    position: absolute;
    background-color: red;
    cursor: pointer;
  }
</style>
</head>
<body>

<div id="draggable">Drag me</div>

<script>
  const element = document.getElementById('draggable');
  let active = false;
  let currentX;
  let currentY;
  let initialX;
  let initialY;
  let xOffset = 0;
  let yOffset = 0;

  element.addEventListener('mousedown', dragStart, false);
  document.addEventListener('mouseup', dragEnd, false);
  document.addEventListener('mousemove', drag, false);

  function dragStart(e) {
    if (e.target === element) {
      active = true;
      currentX = e.clientX - xOffset;
      currentY = e.clientY - yOffset;
      initialX = element.offsetLeft;
      initialY = element.offsetTop;
    }
  }

  function dragEnd(e) {
    initialX = currentX;
    initialY = currentY;
    active = false;
  }

  function drag(e) {
    if (active) {
      e.preventDefault(); // prevent default to allow for objects to be dragged

      let x = e.clientX - currentX;
      let y = e.clientY - currentY;
      let maxX = window.innerWidth - element.offsetWidth;
      let maxY = window.innerHeight - element.offsetHeight;

      // The new X and Y coordinates of the element should be within the boundaries of the window
      x = Math.min(Math.max(x, 0), maxX);
      y = Math.min(Math.max(y, 0), maxY);

      // Calculate the new cursor position:
      xOffset = x - initialX;
      yOffset = y - initialY;

      // Set the element's new position:
      element.style.left = `${x}px`;
      element.style.top = `${y}px`;
    }
  }
</script>

</body>
</html>

这段代码定义了一个可以拖动的红色方块。它通过监听`mousedown`、`mouseup`和`mousemove`事件来实现拖动功能。在拖动开始时记录鼠标和元素的位置,拖动过程中更新元素的位置,拖动结束时重置状态。同时,还考虑了拖动元素时不超过浏览器窗口边界的限制。