我试图在拖动鼠标时检测鼠标方向。当鼠标按钮按下并且用户拖动鼠标时,我希望文本根据鼠标拖动方向向左或向右更改。
这是我的代码。
var divOverlay = document.getElementById ("div"); var dragged = false window.addEventListener('mousedown', function () { dragged = false }) document.addEventListener('mousemove', function () { dragged = true }) window.addEventListener('mouseup', function(e) { if (dragged == true && e.pageX <= 0) { direction = "left" } else if (dragged == true && e.pageX >= 0) { direction = "right" } divOverlay.innerHTML = direction; oldx = e.pageX; }) #div { width: 100px; height: 100px; background: red; } <div id="div"></div>
我不认为我离得太远了,但我无法锻炼我做错了什么,所以我需要一些帮助。
干得好。它只需要一个小的调整。
var divOverlay = document.getElementById ("div"); var dragged = false var oldX = 0; window.addEventListener('mousedown', function (e) { oldX = e.pageX; dragged = false }) document.addEventListener('mousemove', function () { dragged = true }) window.addEventListener('mouseup', function(e) { if (dragged == true && e.pageX < oldX) { direction = "left" } else if (dragged == true && e.pageX > oldX) { direction = "right" } divOverlay.innerHTML = direction; }) #div { width: 100px; height: 100px; background: red; } <div id="div"></div>