클릭 한 x 및 y 좌표의 상대 값과 부모 컨테이너의 오프셋을 확인하여 마우스를 클릭 한 실제 값을 찾으려고합니다. 웹 페이지.마우스 클릭 x 및 y의 정확한 값을 얻으려고 시도 NaN
문제는 다음과 같습니다. NaN을 x 및 y로 화면에 표시하고 있습니까? 이유를 모르십니까?
// get the position of click
function getPosition(el) {
var xPosition = 0;
var yPosition = 0;
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",
};
}
function handleClick(event) {
// Return the current element clicked on
var el = event.currentTarget;
// Return the offset values of the element clicked on
var relOffsetValues = getPosition(el);
// Get the clicked values that is relative to the element
var valuesRelToClickedElementX = event.ClientX;
var valuesRelToClickedElementY = event.ClientY;
// Find the true value of x and y by adding the offset and the to clicked value of x and y
var realValueX = relOffsetValues.x + valuesRelToClickedElementX;
var realValueY = relOffsetValues.y + valuesRelToClickedElementY;
// display the x and y of the mouse click
alert("x:" + realValueX + ", y:" + realValueY);
}
// Set up event handlers according to standards
window.addEventListener("load", function(){
document.addEventListener("click", handleClick);
});
는 clientX가/y는 소문자 C로 시작해야하기 때문에 어쩌면 그것은이다. clientX/clientY. –
해결되었습니다. 아직도 NaN 받기 – Shaz