当用户点击网站上的任何地方时,我想要注册鼠标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",
};
}
点击事件处理程序
onload功能 基于答案的更新 我必须使用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");
}
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");
}
el
定义event.currentTarget
..但是我收到NaN
错误。不确定。请帮忙!
答案 0 :(得分:0)
您有几个语法和属性错误:
将document.onclick = onClickDo(event);
更改为: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);
}