我有一个函数,可以在不使用JQuery的情况下获得最近单击的位置相对于div元素的坐标,JQuery运行良好。
没有jquery(工作):
var Board = document.getElementById("board"); // div element
function mouseListener(e)
{
var posX = e.clientX - Board.getBoundingClientRect().left,
posY = e.clientY - Board.getBoundingClientRect().top
console.log(posX+" : "+posY);
}
window.addEventListener("mousedown", mouseListener,false);
但与之前的代码相比,这个代码使用JQuery并给出不同的坐标
使用jquery(不工作):
var Board = $("#board");
function mouseListener(e)
{
var posX = e.clientX - Number(Board.css("left").replace("px", "")),
posY = e.clientY - Number(Board.css("top").replace("px", ""));
console.log(posX+" : "+posY);
}
$(window).mousedown(mouseListener);
如何在jQuery上正确地编写它,使其像第一段代码一样工作?
使用jQuery,您必须使用.offset()
才能获得与.getBoundingClientRect()
:相同的值
function mouseListener(e) {
var posX = e.clientX - parseFloat(Board.offset().left),
posY = e.clientY - parseFloat(Board.offset().top);
console.log(posX+" : "+posY);
}
jQuery.fn.offset()此处引用;
有三种方法可以附加事件处理程序。用于jQuery<1.7,但仍在较新版本中工作:
$(window).bind('mousedown', mouseListener);
由于使用了jQuery 1.7方法.on()
,它在事件委派方面也具有最大的灵活性:
$(window).on('mousedown', mouseListener);
第三个是您所使用的,它只是一个快捷方式,并在内部调用.on()
。
引用jQuery.fn.bind()--引用jQuery.fn.on()
您所做的一切在逻辑上都是绝对正确的,只是语法上的小错误。
var Board = $("#board");
function mouseListener(e)
{
var posX = e.clientX - Number(Board.css("left").replace("px", "")), //you forgot to put closing braces here and in the next line.
posY = e.clientY - Number(Board.css("top").replace("px", ""));
console.log(posX+" : "+posY);
}
$(window).mousedown(mouseListener);
请确保在id为"#board"的元素中使用了样式left和top,否则输出将为NaN:NaN。