Javascript 获取鼠标在间隔内的位置以使用鼠标移动div
我试图随着鼠标光标的移动移动div,但不知道如何在超时时间内获得最新更新的鼠标位置。也许有更简单的方法Javascript 获取鼠标在间隔内的位置以使用鼠标移动div,javascript,jquery,Javascript,Jquery,我试图随着鼠标光标的移动移动div,但不知道如何在超时时间内获得最新更新的鼠标位置。也许有更简单的方法 var t; $(document).ready(function(){ $("body").on("mousedown", ".heading", function (e) { $("body").data("header_click", true); if ($("body").data("header_click")) {
var t;
$(document).ready(function(){
$("body").on("mousedown", ".heading", function (e) {
$("body").data("header_click", true);
if ($("body").data("header_click")) {
var container = $("#dialog");
container.css("position", "absolute");
t = setInterval(function(){
//some way to get mouse position
var pos = container.position();
container.css({
top: "",//set based on mouse position
left: "",//set based on mouse position
});
}, 100);
}else{
document.clearInterval(t);
}
});
});
$("body").on("mousedown", ".heading", function (e) {
$("body").data("header_click", false);
});
找到的解决方案对我不起作用。您需要绑定到鼠标移动事件并更新文档变量
var currentMousePos = { x: -1, y: -1 };
$(document).on('mousemove', function(event) {
currentMousePos.x = event.pageX;
currentMousePos.y = event.pageY;
});
然后使用这些相对于要拖动的图元绝对位置的位置来计算和更新图元的新位置
$(document).ready(function(){
$("body").on("mousedown", ".heading", function (e) {
$("body").data("header_click", true);
if ($("body").data("header_click")) {
var container = $("#dialog");
container.css("position", "absolute");
var containerPos = container.pos();
var mouseTopOffset = containerPos.top - currentMousePos.y;
var mouseLeftOffset = containerPos.left - currentMousePos.x;
container.css("left", mouseTopOffset +"px");
container.css("top", mouseLeftOffset +"px");
}
}
}
我还没有真正测试过这一点,但理论上应该做你需要做的事情。只是想知道为什么不使用jquery ui库来实现Dragable@Chausser,因为我现在只想从控制台手动运行它,然后将它转换为bookmarklet。这是一个我无法更改的页面,我只想添加拖动模式的功能。好了,没有办法查询鼠标位置-它只在事件对象中可用。因此,您必须设置一个
mousemove
处理程序,并将拖动逻辑放在那里,而不是轮询。@thg435我得出了相同的结论。谢谢你的帮助!