试图获得鼠标点击x和y pos的准确值 - 得到NaN

时间:2017-02-22 03:32:26

标签: javascript onclick mouseevent

尝试识别单击的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 个答案:

答案 0 :(得分:1)

需要纠正2件事情:

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