如何使用 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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 12:55:32  来源:igfitidea点击:

How do I get the opacity of an element using Javascript?

javascriptcssopacity

提问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 styleproperty. You need to look at the getComputedStylemethod to obtain this (and also currentStylefor 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;">