为什么可拖动div不跟随鼠标光标?

问题描述 投票:0回答:1

我需要在光标后拖动一个div,但是我尝试了一些测试,但是它不起作用..我在代码中错了吗?在按下鼠标后,我需要div移动。...,跟随鼠标,光标...

#dragdiv {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  margin: 50px;
}
<div id="container">
    <div id="dragdiv"></div>
</div>
   window.addEventListener('mouseup', mouseUpElement, false);
   document.getElementById("dragdiv").addEventListener('mousedown', mouseDownElement, false);

   function mouseDownElement() {
   window.addEventListener("mousemove", myFunctionDragElement, true);
   document.getElementById("dragdiv").style.cursor = "pointer";
   }

   function mouseUpElement() {
   window.removeEventListener("mousemove", myFunctionDragElement, true);
   document.getElementById("dragdiv").style.cursor = "auto";
   }

   function myFunctionDragElement(e) {

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

   var oTop = document.getElementById("dragdiv").offsetTop;
   var oLeft = document.getElementById("dragdiv").offsetLeft;

   document.getElementById("dragdiv").style.position = "absolute";
   document.getElementById("dragdiv").style.left = x - oTop + "px" ;
   document.getElementById("dragdiv").style.top = y - oLeft + "px";

   }
javascript cursor mouse drag
1个回答
0
投票

您可以为div设置transform,并取消使用偏移量:

var dragDiv = document.getElementById("dragdiv")
window.addEventListener('mouseup', mouseUpElement, false);
dragDiv.addEventListener('mousedown', mouseDownElement, false);

function mouseDownElement() {
  window.addEventListener("mousemove", myFunctionDragElement, true);
  dragDiv.style.cursor = "pointer";
}

function mouseUpElement() {
  window.removeEventListener("mousemove", myFunctionDragElement, true);
  dragDiv.style.cursor = "auto";
}

function myFunctionDragElement(e) {
  var x = e.clientX;
  var y = e.clientY;
  dragDiv.style.left = x  + "px";
  dragDiv.style.top = y  + "px";
}
#dragdiv {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  top: 50px;
  left: 50px;
  transform: translate(-50%, -50%);
}
<div id="dragdiv"></div>
© www.soinside.com 2019 - 2024. All rights reserved.