如何返回由事件侦听器调用的函数的值?

时间:2013-11-08 20:14:56

标签: javascript function return coordinates addeventlistener

我想要通过" getPosition"计算坐标。可以与其他函数一起使用,这样我就不必编写在getPosition中使用x和y的其余代码。

我知道我可以使用return {posX:x,posY:y}之类的东西;从函数中检索这两个值,但我不知道如何在getPosition之外使它们可用。

document.addEventListener("DOMContentLoaded", init, false);

  function init()
  {
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousedown", getPosition, false);
  }

   function getPosition(event)
  {
    var x = new Number();
    var y = new Number();
    var canvas = document.getElementById("canvas");

    if (event.x != undefined && event.y != undefined)
    {
      x = event.x;
      y = event.y;
    }
    else // Firefox method to get the position
    {
      x = event.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = event.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
    }

    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;

  }

1 个答案:

答案 0 :(得分:3)

创建一个闭包并将变量x和y以及使用它们的函数放在那里:

(function(){
  var _x = 0;
  var _y = 0;

  document.addEventListener("DOMContentLoaded", init, false);

  function init()
  {
    var canvas = document.getElementById("canvas");
    canvas.addEventListener("mousedown", getPosition, false);
  }

   function getPosition(event)
  {
    var x = new Number();
    var y = new Number();
    var canvas = document.getElementById("canvas");

    if (event.x != undefined && event.y != undefined)
    {
      x = event.x;
      y = event.y;
    }
    else // Firefox method to get the position
    {
      x = event.clientX + document.body.scrollLeft +
          document.documentElement.scrollLeft;
      y = event.clientY + document.body.scrollTop +
          document.documentElement.scrollTop;
    }

    x -= canvas.offsetLeft;
    y -= canvas.offsetTop;

    //Save x and y for later
    _x = x;
    _y = y;
  }
})();