我使用jQuery。点击来处理Raphael图形上的鼠标点击事件,同时,我需要处理鼠标拖动事件,鼠标拖动在Raphael中由鼠标下拉,鼠标上拉和鼠标移动组成。
很难区分点击和拖动,因为点击也包含鼠标下拉和鼠标上拉,我怎么能区分鼠标“点击”和鼠标“拖动”然后在Javascript?
我使用jQuery。点击来处理Raphael图形上的鼠标点击事件,同时,我需要处理鼠标拖动事件,鼠标拖动在Raphael中由鼠标下拉,鼠标上拉和鼠标移动组成。
很难区分点击和拖动,因为点击也包含鼠标下拉和鼠标上拉,我怎么能区分鼠标“点击”和鼠标“拖动”然后在Javascript?
当前回答
有同样的问题,最近在一个树列表中,用户可以点击项目或拖动它,使这个小指针类,并把它放在我的utils.js
function Pointer(threshold = 10) {
let x = 0;
let y = 0;
return {
start(e) {
x = e.clientX;
y = e.clientY;
},
isClick(e) {
const deltaX = Math.abs(e.clientX - x);
const deltaY = Math.abs(e.clientY - y);
return deltaX < threshold && deltaY < threshold;
}
}
}
下面你可以看到它的工作原理:
function Pointer(threshold = 10) { let x = 0; let y = 0; return { start(e) { x = e.clientX; y = e.clientY; }, isClick(e) { const deltaX = Math.abs(e.clientX - x); const deltaY = Math.abs(e.clientY - y); return deltaX < threshold && deltaY < threshold; } } } const pointer = new Pointer(); window.addEventListener('mousedown', (e) => pointer.start(e)) //window.addEventListener('mousemove', (e) => pointer.last(e)) window.addEventListener('mouseup', (e) => { const operation = pointer.isClick(e) ? "Click" : "Drag" console.log(operation) })
其他回答
下面的编码是检测鼠标的移动。
它适用于大多数情况。这也取决于 关于如何将mouseevent处理为单击。 在JavaScript中,检测非常简单。它不关心如何 在鼠标下拉和鼠标上拉之间按住或移动。 Event.detail不会重置为1当你的鼠标移动 鼠标下拉和鼠标上拉。 如果你需要区分点击和长按,你需要 检查事件的差异。时间戳。
// ==== add the code at the begining of your coding ==== let clickStatus = 0; (() => { let screenX, screenY; document.addEventListener('mousedown', (event) => ({screenX, screenY} = event), true); document.addEventListener('mouseup', (event) => (clickStatus = Math.abs(event.screenX - screenX) + Math.abs(event.screenY - screenY) < 3), true); })(); // ==== add the code at the begining of your coding ==== $("#draggable").click(function(event) { if (clickStatus) { console.log(`click event is valid, click count: ${event.detail}`) } else { console.log(`click event is invalid`) } }) <!doctype html> <html lang="en"> <!-- coding example from https://jqueryui.com/draggable/ --> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>jQuery UI Draggable - Default functionality</title> <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <link rel="stylesheet" href="/resources/demos/style.css"> <style> #draggable { width: 150px; height: 150px; padding: 0.5em; } </style> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <script> $( function() { $( "#draggable" ).draggable(); } ); </script> </head> <body> <div id="draggable" class="ui-widget-content"> <p>Drag me around</p> </div> </body> </html>
正如mrjrdnthms在他对接受的答案的评论中指出的那样,这不再适用于Chrome(它总是触发鼠标移动),我已经改编了Gustavo的答案(因为我使用jQuery)来解决Chrome的行为。
var currentPos = [];
$(document).on('mousedown', function (evt) {
currentPos = [evt.pageX, evt.pageY]
$(document).on('mousemove', function handler(evt) {
currentPos=[evt.pageX, evt.pageY];
$(document).off('mousemove', handler);
});
$(document).on('mouseup', function handler(evt) {
if([evt.pageX, evt.pageY].equals(currentPos))
console.log("Click")
else
console.log("Drag")
$(document).off('mouseup', handler);
});
});
Array.prototype.equals函数来自这个答案
基于这个答案,我在React组件中这样做:
export default React.memo(() => {
const containerRef = React.useRef(null);
React.useEffect(() => {
document.addEventListener('mousedown', handleMouseMove);
return () => document.removeEventListener('mousedown', handleMouseMove);
}, []);
const handleMouseMove = React.useCallback(() => {
const drag = (e) => {
console.log('mouse is moving');
};
const lift = (e) => {
console.log('mouse move ended');
window.removeEventListener('mousemove', drag);
window.removeEventListener('mouseup', this);
};
window.addEventListener('mousemove', drag);
window.addEventListener('mouseup', lift);
}, []);
return (
<div style={{ width: '100vw', height: '100vh' }} ref={containerRef} />
);
})
这应该能很好地工作。类似于已接受的答案(虽然使用jQuery),但只有当新的鼠标位置与mousedown事件上的位置不同时,isdrag标志才会重置。与公认的答案不同,这适用于最新版本的Chrome,无论鼠标是否移动,鼠标移动都会被触发。
var isDragging = false;
var startingPos = [];
$(".selector")
.mousedown(function (evt) {
isDragging = false;
startingPos = [evt.pageX, evt.pageY];
})
.mousemove(function (evt) {
if (!(evt.pageX === startingPos[0] && evt.pageY === startingPos[1])) {
isDragging = true;
}
})
.mouseup(function () {
if (isDragging) {
console.log("Drag");
} else {
console.log("Click");
}
isDragging = false;
startingPos = [];
});
你也可以在鼠标移动中调整坐标检查,如果你想增加一点公差(即将微小的移动视为点击,而不是拖动)。
如果您希望检查特定元素的单击或拖动行为,则无需监听主体即可执行此操作。
$(document).ready(function(){ let click; $('.owl-carousel').owlCarousel({ items: 1 }); // prevent clicks when sliding $('.btn') .on('mousemove', function(){ click = false; }) .on('mousedown', function(){ click = true; }); // change mouseup listener to '.content' to listen to a wider area. (mouse drag release could happen out of the '.btn' which we have not listent to). Note that the click will trigger if '.btn' mousedown event is triggered above $('.btn').on('mouseup', function(){ if(click){ $('.result').text('clicked'); } else { $('.result').text('dragged'); } }); }); .content{ position: relative; width: 500px; height: 400px; background: #f2f2f2; } .slider, .result{ position: relative; width: 400px; } .slider{ height: 200px; margin: 0 auto; top: 30px; } .btn{ display: flex; align-items: center; justify-content: center; text-align: center; height: 100px; background: #c66; } .result{ height: 30px; top: 10px; text-align: center; } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" /> <div class="content"> <div class="slider"> <div class="owl-carousel owl-theme"> <div class="item"> <a href="#" class="btn" draggable="true">click me without moving the mouse</a> </div> <div class="item"> <a href="#" class="btn" draggable="true">click me without moving the mouse</a> </div> </div> <div class="result"></div> </div> </div>