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

爱⌒轻易说出口 提交于 2019-11-27 05:59:08

问题


If I have:

#em {
  opacity:0.5;
}

How do I get #em's opacity using javascript? :D

I've got troubles with the following (it returns nothing):

return document.getElementById("em").style.opacity;

回答1:


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




回答2:


var em = document.getElementById("em");
var  temp = window.getComputedStyle(em).getPropertyValue("opacity");

Now, the variable temp will have the value of opacity of "em".




回答3:


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


来源:https://stackoverflow.com/questions/11365296/how-do-i-get-the-opacity-of-an-element-using-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!