[英]Using mousedown-position in mouseup-event
Hey guys I am trying an easy custom-made drag and drop system of an element. 大家好,我正在尝试一个简单的元素定制拖放系统。 I wanna use the mousedown and mouseup event for that. 我想为此使用mousedown和mouseup事件。
My problem is that I dont know how to get the mousedown-position in the mouseup-event. 我的问题是我不知道如何在mouseup事件中获取mousedown位置。
div.mousedown(function (e) {
var cursorDown = e.pageX;
}).mouseup(function (e) {
alert(cursorDown)
})
I tried to modify the solution from here to only get the first and last value, but I failed: How can I retrieve all mouse coordinates between mousedown to mouseup event 我试图从此处修改解决方案以仅获取第一个和最后一个值,但是失败了: 如何获取在mousedown到mouseup事件之间的所有鼠标坐标
I appreciate every tip ypu can give me 我感谢ypu可以给我的每条小费
Thank you in advance 先感谢您
You need to store it outside the event handler. 您需要将其存储在事件处理程序之外。
Either in a variable (if they'll only ever be one or it's wrapped in a plugin) - or, to keep it self-contained, against the item: 要么在变量中(如果它们只能是一个变量,要么被包装在插件中)-或者,为了使其自成一体,针对该项目:
div.mousedown(function (e) {
$(this).data("cursorDown", e.pageX)
}).mouseup(function (e) {
var cursorDown = $(this).data("cursorDown")
alert(cursorDown)
})
To modify the other solution: 修改其他解决方案:
var allPoints = [];
div.mousedown(function (e) {
$(this).on("mousemove", trackPoints);
}).mouseup(function (e) {
$(this).off("mousemove", trackPoints);
var cursorDown = allPoints[0];
allPoints = []; // clear drag details
});
function trackPoints(e) {
allPoints.push({ x: e.pageX, y: e.pageY });
}
or, using a variable 或者,使用变量
var cursorDown = {};
div.mousedown(function (e) {
cursorDown = { x: e.pageX, y: e.pageY };
}).mouseup(function (e) {
alert(cursorDown)
});
You could use the data-* attribute with the jQuery's .data() Method 您可以将data- *属性与jQuery的.data()方法一起使用
$('#box').on({ mousedown(evt) { $(this).data('xyDn', {x: evt.pageX, y: evt.pageY}); }, mouseup(evt) { const xyDn = $(this).data('xyDn'); const xyUp = {x: evt.pageX, y: evt.pageY}; console.log(` DN = x:${xyDn.x} y:${xyDn.y} UP = x:${xyUp.x} y:${xyUp.y} `); }, });
html, body { height: 100%; margin: 0; } #box { width: 100vw; height: 100vh; }
<div id="box"></div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.