【问题标题】:2 number subtracted from each other make a NaN?2个数字相减得到一个NaN?
【发布时间】:2017-09-30 03:06:59
【问题描述】:

我正在尝试将 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;

【问题讨论】:

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

标签: javascript nan


【解决方案1】:

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

p2({pageY: 100}, 50)

将记录false

【讨论】:

  • @Collin 这是这个答案之上的一个工作示例,这基本上是我想回答的:) EXAMPLE
【解决方案2】:

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,我认为这种编码风格更好,但您可以随心所欲(性能差异很小甚至没有)。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-10-04
    • 2022-01-11
    • 2022-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-19
    相关资源
    最近更新 更多