试图在屏幕上打印出鼠标x和y pos - 获得0,0

时间:2017-02-21 23:14:11

标签: javascript onclick event-handling

当用户点击网站上的任何地方时,我想要注册鼠标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",
  };
}
点击事件处理程序

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");

 }

我必须使用el定义event.currentTarget ..但是我收到NaN错误。不确定。请帮忙!

1 个答案:

答案 0 :(得分:0)

您有几个语法和属性错误:

document.onclick = onClickDo(event);更改为:document.onclick = onClickDo;

您不会将事件传递给事件处理函数。这会自动发生。而且,编写代码的方式是立即调用onClicDo而不是等待点击事件。

此外,event.CurrentTarget应该是:event.currentTargetel.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);
}