无法从Javascript访问CSS Selector的属性

5 html javascript css

这是一个非常基本的问题:为什么下面代码中的finishLoading()函数无法访问#myStyle CSS选择器的'opacity'属性?警报不会显示任何内容,我已经确认"不透明度"属性为"false".

非常感谢!

<html>
<head>
<style type="text/css">
<!--
#myStyle
{
    opacity: 0.50;
}
-->
</style>

<script type="text/javascript">
<!--
function finishedLoading()
{
    alert(document.getElementById('myStyle').style.opacity);
}
-->
</script> 
</head>
<body onload="finishedLoading();">

    <div id="myStyle">
        hello
    </div>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

rah*_*hul 5

您只能在计算后才能获取通过类设置的值.

var oElm = document.getElementById ( "myStyle" );
var strValue = "";
if(document.defaultView && document.defaultView.getComputedStyle)
{
strValue = document.defaultView.getComputedStyle(oElm, null).getPropertyValue("-moz-opacity");
}
else if(oElm.currentStyle)    // For IE
{
strValue = oElm.currentStyle["opacity"];
}

alert ( strValue );
Run Code Online (Sandbox Code Playgroud)

  • 评论规则!currentStyle处理IE的方式,其他任何人都支持getComputedStyle().document.defaultView是一种获取负责呈现文档的"窗口"的方法.顺便说一句,`-moz-opacity`将不再起作用(因为FF 2,在Opera和WebKit中它从未这样做过). (2认同)

Tom*_*Tom 0

我建议你看看jQuery和Learning jQuery上的一些帖子,它会让做这样的事情变得非常容易。