这个问题背后一个我昨天问过的问题。那个问题是:
"if" statement parameters not functioning as intended. JavaScript
但是现在我实现以下代码时出现 NaN 错误:
var targetBoxLeft = parseFloat(document.getElementById("targetBox").style.left);
bulletOne.style.left = bulletOneLeft;
if (bulletOneLeft > targetBoxLeft){
document.getElementById("targetBox").style.opacity = "0";
};
昨天我没有使用" parseFloat"但是我的问题是,如果我特意将targetBoxLeft的参数描述为CSS style.left属性;为什么这不是一个特定的数字?为什么它不会占用左数:310px;由元素属性本身指定?
#targetBox{
position: absolute;
background-color: green;
height: 20px;
width: 20px;
top: 30px;
left: 310px;
opacity: 1;
}
逻辑上,以下两行代码是否应检测到ACTUAL数字?
var bulletOneLeft = bulletOne.style.left;
var targetBoxLeft = targetBox.style.left;
然后,一旦上述变量被检测为实际数字,以下 if 语句代码是否能够在任何给定时间根据它们的值进行比较( bulletOneLeft ++; )涉及?:
if (bulletOneLeft > targetBoxLeft){
document.getElementById("targetBox").style.opacity = "0";
};
我不完全确定发生了什么,但因为我的代码读取了targetBox.style.left时出现了NaN错误,我猜测CSS属性可能需要额外的代码转换成在运行带有相应 VAR 的 if 语句之前的实际数字/变量?
答案 0 :(得分:3)
您正在查询.style.left
属性,该属性与计算样式不同。元素引用的.style
属性style
属性值。 parseFloat("")
返回NaN
。使用window.getComputedStyle()
var div = document.querySelector("div");
console.log(div.style.left, parseFloat(div.style.left));
console.log(parseFloat(window.getComputedStyle(div).getPropertyValue("left")));

div {
position: relative;
left:310px;
}

<div>div</div>
&#13;