如何使用 Javascript 获取元素的不透明度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11365296/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the opacity of an element using Javascript?
提问by John
If I have:
如果我有:
#em {
opacity:0.5;
}
How do I get #em
's opacity using javascript
? :D
我如何获得#em
不透明度使用javascript
?:D
I've got troubles with the following (it returns nothing):
我遇到了以下问题(它什么都不返回):
return document.getElementById("em").style.opacity;
采纳答案by Graham
Setting a CSS value in a stylesheet is not the same as setting it through the style
property. You need to look at the getComputedStyle
method to obtain this (and also currentStyle
for older IE).
在样式表中设置 CSS 值与通过style
属性设置它不同。您需要查看getComputedStyle
获取此信息的方法(也currentStyle
适用于较旧的 IE)。
回答by Sajib Biswas
var em = document.getElementById("em");
var temp = window.getComputedStyle(em).getPropertyValue("opacity");
Now, the variable tempwill have the value of opacity of "em".
现在,变量temp的不透明度值为“em”。
回答by mohsin
document.getElementById("em").style.opacity;
it will work fine if you use inline style .eg.
如果您使用内联样式,它将正常工作。例如。
<div id="em" style="width: 50px; height: 50px; opacity: 0.5;">