0

我有一个简单的事件监听器,我试图将变量传递给一个函数,但它不起作用......这就是我所拥有的:

window.onload = function () {
    document.getElementById('cursor').addEventListener("mousedown", mousePos, false);
}

function mousePos(e) {
    var x = e.clientX;
    var y = e.clientY;
    document.getElementById('cursor').addEventListener("mousemove", function () {
        mousemoveCalc(x, y);
    }, false);
}

function mousemoveCalc(e, x, y) {
    console.log(e);
    console.log(x); //undefined
    console.log(y); //undefined
}

我变得不确定xy但我不知道如何解决它=/它们在mousePos中没有定义=/

我该如何解决 ?

4

1 回答 1

0

看看这个小提琴,看看这是否接近你正在寻找的东西。 http://jsfiddle.net/cF6fE/2/

  var posx = 0;
    var posy = 0;
    window.onload = function() {

        document.getElementById('cursor').addEventListener("mousedown", mousePos, false);
    }

    function mousePos(e) {
        posx = e.clientX;
        posy = e.clientY;
        document.getElementById('cursor').addEventListener("mousemove", mousemoveCalc);
    }

    function mousemoveCalc(e) {
        console.log(e);
      var x = e.clientX;
        var y = e.clientY;
    var xOffset  = posx-x;
    var yOffset  = posy-y;
        console.log(x); 
        console.log(y); 
     console.log(xOffset); 
        console.log(yOffset); 
    }

更新:- 使用Function.bind

http://jsfiddle.net/uGuHk/

function mousePos(e) {
        var posx = e.clientX;
        var posy = e.clientY;
        document.getElementById('cursor').addEventListener("mousemove", mousemoveCalc.bind(this, posx,posy));
    }

    function mousemoveCalc(xax,yax,e) {

        console.log(e);
      var x = e.clientX;
        var y = e.clientY;
    var xOffset  = xax-x;
    var yOffset  = yax-y;
        console.log(x); //undefined
        console.log(y); //undefined
     console.log(xOffset); //undefined
        console.log(yOffset); //undefined
    }

更新2:-关闭

http://jsfiddle.net/FG6uW/

function mousePos(e) {
        var posx = e.clientX;
        var posy = e.clientY;
        document.getElementById('cursor').addEventListener("mousemove", function() {
            (function(x, y) {
                mousemoveCalc(x, y)
            })(posx, posy)
        });
    }

    function mousemoveCalc(xax, yax) {

        var x = event.clientX;
        var y = event.clientY;
        var xOffset = xax - x;
        var yOffset = yax - y;
        console.log(xax);
        console.log(yax);

        document.getElementById('cursor').innerText = xax + '-' + yax + '|' + xOffset + '-' + yOffset;
        console.log(xOffset);
        console.log(yOffset);
    }
于 2013-04-02T02:46:57.417 回答