当用户单击网站上的任何位置时,我想注册鼠标x和y pos,并希望将其打印出来。
问题:它每次都打印出0,0位置。
此功能获得x和y
的位置 // get the position of click
function getPosition(el) {
var xPosition = 0;
var yPosition = 0;
while (el) {
if (el.tagName == "BODY") {
// deal with browser quirks with body/window/document and page scroll
var xScrollPos = el.scrollLeft || document.documentElement.scrollLeft;
var yScrollPos = el.scrollTop || document.documentElement.scrollTop;
xPosition += (el.offsetLeft - xScrollPos + el.clientLeft);
yPosition += (el.offsetTop - yScrollPos + el.clientTop);
} else {
xPosition += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPosition += (el.offsetTop - el.scrollTop + el.clientTop);
}
el = el.offsetParent;
}
return {
x: xPosition,
y: yPosition,
a: "hahah",
};
}
在单击事件处理程序
function onClickDo(event) {
var el = event.CurrentTarget;
var posOb = getPosition(el);
for (var key in posOb) {
console.log(key);
}
alert(posOb.x + " x pos");
alert(posOb.y+ " y pos");
alert(posOb.a+ " random string");
}
onload函数
window.onload = function() {
document.onclick = onClickDo(event);
};
基于答案
更新 // Set up event handlers according to modern standards
window.addEventListener("load", function(){
document.addEventListener("click", handleClick);
});
function handleClick(event) {
var xPosition = 0;
var yPosition = 0;
var el = event.currentTarget; <----------------------- targeting the element not working
while (el) {
if (el.nodeName == "BODY") {
// deal with browser quirks with body/window/document and page scroll
var xScrollPos = el.scrollLeft || document.documentElement.scrollLeft;
var yScrollPos = el.scrollTop || document.documentElement.scrollTop;
xPosition += (el.offsetLeft - xScrollPos + el.clientLeft);
yPosition += (el.offsetTop - yScrollPos + el.clientTop);
} else {
xPosition += (el.offsetLeft - el.scrollLeft + el.clientLeft);
yPosition += (el.offsetTop - el.scrollTop + el.clientTop);
}
el = el.offsetParent;
}
// return {
// x: xPosition,
// y: yPosition,
// a: "hahah",
// };
alert(xPosition + " x pos" + " and " + yPosition + " y pos");
}
我必须使用event.currentTarget
定义el
..但是我遇到了NaN
错误。不确定。请帮助!
您有几个语法和属性错误:
更改: document.onclick = onClickDo(event);
to: document.onclick = onClickDo;
您不会将事件传递给事件处理功能。这会自动发生。而且,编写代码的方式,立即调用onClicDo
而不是等待点击事件。
另外,event.CurrentTarget
应该是:event.currentTarget
和 el.tagName
应该是:el.nodeName
这是一个非常缩小的版本,可以显示基本设置。
// Set up event handlers according to modern standards
window.addEventListener("load", function(){
document.addEventListener("click", handleClick);
});
function handleClick(event) {
alert("x:" + event.offsetX + ", y:" + event.offsetY);
}