首页 > 解决方案 > 为什么通过 mousemove 旋转 div 不起作用 javascript?

问题描述

我想要的是让 div 从 0 旋转到 360 而没有 -。旋转应顺时针从 0 度到 360 度。在这段代码中,它的范围从 0 到 180 和从 -180 到 0。

第二个问题:每次我点击“rotator div”我的位置都会改变???

代码:

document.getElementById("rotator").addEventListener('mousedown', mouseDownRotator, false);


function mouseDownRotator(e) {
  window.addEventListener("mousemove", mouseMoveRotator, true);
}

function mouseMoveRotator(e) {

  window.addEventListener('mouseup', mouseUpRotator, true);
  var arrow = document.getElementById("rotator");
  var arrowRects = document.getElementById("dragdiv").getBoundingClientRect();
  var center_x = (arrowRects.left) + (arrowRects.width / 2);
  var center_y = (arrowRects.top) + (arrowRects.height / 2);
  var mouse_x = e.pageX;
  var mouse_y = e.pageY;
  var radians = Math.atan2(mouse_x - center_x, mouse_y - center_y);
  document.getElementById("dragdiv").style.transform = "rotate(" + (radians * (180 / Math.PI) * -1) + 90 + "deg)";
}

function mouseUpRotator() {
  window.removeEventListener("mousemove", mouseMoveRotator, true);


}
#dragdiv {
  width: 100px;
  height: 100px;
  background-color: red;
  position: absolute;
  margin: 250px;
}

#rotator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background: white;
  border: 3px solid #4286f4;
  position: absolute;
  top: -50px;
  right: 43%;
  cursor: nwse-resize;
}
<div id="container">
  <div id="dragdiv"></div>
</div>

标签: javascriptrotationmousemovemousedowndegrees

解决方案


推荐阅读