<html>
<head>
<title>Return Width</title>
<style type="text/css">
#foo { background: green; width: 80px; }
</style>
<script type="text/javascript">
function getWidth() {
alert(document.getElementById("foo").style.width);
}
</script>
</head>
<body>
<div id="foo" onClick="getWidth()">
Hello World
</div>
我一直在尝试返回多个属性,包括 width
和 backgroundColor
,我发现我可以设置这些属性,但无法返回它们。为什么?
最佳答案
这只适用于内联样式。使用getComputedStyle用于通过非内联样式设置的 CSS。
function getWidth() {
var elem = document.getElementById("foo");
var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("width");
alert(theCSSprop);
}
<强> jsFiddle example
关于javascript - 为什么 JavaScript 不返回样式属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14911516/