为什么这样有效:
newDiv.style.top = topBar.style.height.split("px")[0]+"px";
->>><div style="top: 30.31px;" class="lineSeparator"></div>
Run Code Online (Sandbox Code Playgroud)
这也有效
newDiv.style.top = topBar.style.height.split("px")[0]-2+"px";
->>><div style="top: 28.31px;" class="lineSeparator"></div>
Run Code Online (Sandbox Code Playgroud)
这也有效
newDiv.style.top = topBar.style.height.split("px")[0]/2+"px";
->>><div style="top: 15.15px;" class="lineSeparator"></div>
Run Code Online (Sandbox Code Playgroud)
但这不起作用:
newDiv.style.top = topBar.style.height.split("px")[0]+2+"px";
->>><div style="top: 30.31px;" class="lineSeparator"></div>
Run Code Online (Sandbox Code Playgroud)
我也尝试过:
newDiv.style.top = (topBar.style.height.split("px")[0]+2)+"px";
Run Code Online (Sandbox Code Playgroud)
这是我的完整代码:
function generateSeparators(n){
for(var i=0;i<n;i++){
var newDiv=document.createElement("div");
newDiv.style.top = topBar.style.height.split("px")[0]+"px";
newDiv.className = "lineSeparator";
sideBar.appendChild(newDiv);
}
}
Run Code Online (Sandbox Code Playgroud)
在+Javascript中操作,不像/并且-,还执行字符串连接.您必须先将第一个字符串操作数强制转换为数字.否则,"字符串"部分将压倒"数字"部分.例如:
"3" + 2 --> "32"
Run Code Online (Sandbox Code Playgroud)
这将是修复代码的一种方法:
newDiv.style.top = ((+topBar.style.height.split("px")[0])+2)+"px";
Run Code Online (Sandbox Code Playgroud)
这可能是一种更好,更清晰的方式:
newDiv.style.top = (parseInt(topBar.style.height.split("px")[0], 10) + 2) + "px";
Run Code Online (Sandbox Code Playgroud)
(parseInt的10个参数意味着将字符串解释为基数为10的数字.有关详细信息,请参阅文档:https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/parseInt)
| 归档时间: |
|
| 查看次数: |
133 次 |
| 最近记录: |