【发布时间】:2013-02-01 14:55:56
【问题描述】:
我尝试使用 javascript 访问 div 的宽度, 但无论我设置什么,它每次都在打印 NaN。 我是 javascript 新手,我的代码有什么问题?
<html>
<head>
<title>hello</title>
<style type="text/css">
#base
{
width:300px;
height:30px;
background-color: black;
}
#scr
{
height:30px;
width:10px;
background-color: red;
}
</style>
<script type="text/javascript">
var magic = function()
{
console.log("inside magic")
var d = document.getElementById("scr");
var b = d.style.width;
console.log(b);
b = parseInt(b);
console.log(b);
}
</script>
</head>
<body>
<div id="base">
<div id = "scr" >
</div>
</div>
<br>
<button onclick="magic()">Magic</button>
</body>
</html>
【问题讨论】:
-
@user1263375:我没有看到使用 jQuery 接受的答案。您现在接受的答案与另一个问题的答案相同。
-
style属性其实就是元素的属性style。因此,当您拥有
element.style 实际上是在引用样式中包含的内容。在你的情况下,如果你有 ...style="width:20px;"然后 element.style 将打印 20px。 -
您想要的不是属性,而是元素本身的计算属性。在这种情况下,使用纯 javascript 通常最容易使用 width = element.offsetWidth || element.clientWidth || element.scrollHeight;
标签: javascript html css