gpt4 book ai didi

javascript - 尝试获取鼠标单击 x 和 y pos 的准确值 - 得到 NaN

转载 作者:行者123 更新时间:2023-12-03 04:57:19 25 4
gpt4 key购买 nike

尝试识别点击的x和y坐标的相对值以及父容器的偏移量,以找到鼠标在网页上点击的真实值。

问题是:我在屏幕上将 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);
});

最佳答案

需要纠正两件事才能正常工作:

  1. event.ClientX 设为 event.clientX,将 event.ClientY 设为 event.clientY。请注意 clientX 和 clientY 中的小写字母。
  2. 使用 document.body,而不是 document.addEventListener("click", handleClick);。 addEventListener("click",handleClick);

维诺德

关于javascript - 尝试获取鼠标单击 x 和 y pos 的准确值 - 得到 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42382203/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com