![](/img/trans.png)
[英]Why won't this function work in an Object-Oriented style of javascript?
[英]Why won't javascript return the style properties?
<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);
}
style
属性引用直接应用于元素的style
(通过style
属性或style
属性)。 它不引用通过级联应用的样式。
为此,您需要getComputedStyle
。
根据您需要访问的属性,您可以使用其他方法,例如offsetwidth
和offsetheight.
getComputedStyles在ie7和ie8上不起作用,尽管可以尝试,但它是跨浏览器的
function getStyle(el, cssprop){
if (el.currentStyle) //IE
return el.currentStyle[cssprop]
else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox
return document.defaultView.getComputedStyle(el, "")[cssprop]
else //try and get inline style
return el.style[cssprop]
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.