无法从JavaScript访问CSS选择器的属性 [英] Can't Access CSS Selector's Properties from Javascript

查看:80
本文介绍了无法从JavaScript访问CSS选择器的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里有一个非常基本的问题:为什么下面的代码中的finishLoading()函数不能访问#myStyle CSS选择器的'opacity'属性?警告不显示任何内容,我已验证opacity属性为false。

Here's a very basic question: why is the finishLoading() function in the code below not able to access the 'opacity' property for the #myStyle CSS selector? The alert doesn't display anything, and I've verified that the 'opacity' property is '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>


推荐答案

计算。

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 );

这篇关于无法从JavaScript访问CSS选择器的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆