2017-09-29 90 views
0

我想从对方减去2个整数,但我仍然得到NaN。 谁能请解释一下什么是错我的代码2个数相减得到一个NaN?

var moveit = null; 
p = function (e){ 

if ((e.target.id == "windowContainer") || (e.target.id == 
"windowContainer2") || (e.target.id == "windowContainer3")){ 
    console.log (e); 
    window.moveit = e.target; 
    window.onmousemove = p2; 
    var r = window.moveit.getBoundingClientRect(); 
    var rl = r.left; 
    var rt = r.top; 

    window.onmouseup = function (e){ 
    if (window.moveit == null) return; 
     window.moveit.onmousemove = window.moveit = null; 
    } 
} 
} 

p2 = function (e, rt, epageY){ 
    if (window.moveit == null) return; 
    var newY = rt - e.pageY; 
    console.log(isNaN(newY)); 
} 
document.getElementById('windowContainer').onmousedown = p; 
document.getElementById('windowContainer2').onmousedown = p; 
document.getElementById('windowContainer3').onmousedown = p; 
+2

为什么你认为你有两个整数? 'rt'没有任何价值。 – SLaks

回答

0

的的OnMouseMove /降功能只能传递一个参数的处理程序 - 一个Event对象。在这种情况下,ep2中唯一定义的参数。自己调用函数来测试它是否正常工作:

p2({pageY: 100}, 50) 

将会记录false

+0

@Collin下面是这个答案的基础上的一个工作示例,基本上我想回答:) [示例](https://jsfiddle.net/a58bysjg/) –

0

rt是不是一个值,这是造成你的问题。您需要将其传入您的onmousemove事件

var moveit = null; 
p = function(e) { 
    if (
    e.target.id == "windowContainer" || 
    e.target.id == "windowContainer2" || 
    e.target.id == "windowContainer3" 
) { 
    console.log(e); 
    window.moveit = e.target; 
    var r = window.moveit.getBoundingClientRect(); 
    var rl = r.left; 
    var rt = r.top; 
    window.addEventListener("mousemove", function(e) { 
     p2(e, rt); 
    }); 
    window.onmouseup = function(e) { 
     if (window.moveit == null) return; 
     window.moveit.onmousemove = window.moveit = null; 
    }; 
    } 
}; 

p2 = function(e, rt, epageY) { 
    if (window.moveit == null) return; 
    var newY = rt - e.pageY; 
    console.log(newY); 
}; 
document.getElementById("windowContainer").onmousedown = p; 
document.getElementById('windowContainer2').onmousedown = p; 
document.getElementById('windowContainer3').onmousedown = p; 

此代码块将正常工作。这是我改变的事情的清单:

  1. 我加的addEventListener,而不是.onmousemove,我认为这是更好的编码风格,但你愿意,你可以做(​​的性能差异是最小的为none)。

  2. 在mousemove事件中,我创建了一个匿名函数,以便您可以从上面计算的值中通过rt。