1
當用戶在網站上的任何地方點擊時,我想註冊鼠標x和y位置並希望將其打印出來。試圖在屏幕上打印出鼠標x和y位置 - 獲取0,0
問題:每次打印出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
錯誤。不確定。請幫忙!
「onClicDo被調用的立即而不是等待click事件」 - 我知道這就是問題所在。什麼是解決任何想法? – Shaz
@Shaz我已經給你解決方案,按我指定的方式更改代碼。 –
所以我相信event.offsetX是相對於父母,因此不會給我正確的線。在handlerClick函數中,我做了以下更改。請在答案中查看更新的代碼。幫幫我! – Shaz