opacity and style undefined when accesing element in js but defined in css

前端 未结 4 1022
南方客
南方客 2021-01-19 14:27

With this fiddle http://jsfiddle.net/mungbeans/f2ne6/2/

why is the opacity undefined when accessed in js when its defined in the css?

I presume the answer is

4条回答
  •  清酒与你
    2021-01-19 15:28

    It's because the style property of an HTML element (in the DOM) does not contain the computed style, it contains the immediately defined style of the element. Consider the following HTML:

    If you call document.getElementById("one").style.width, you'll get "50px" back. However, if you remove the style attribute and instead use CSS to style the div to have a width of 50 pixels, it will return "". You can see this in action here:

    http://jsfiddle.net/aAbJY/

    You're probably looking for the computed style, which can be obtained in most browsers using getComputedStyle(). It doesn't work in IE until IE9, though there's probably a way to do it in IE<9. The computed style will return the opacity no matter where it's defined. See an updated example with getComputedStyle() here:

    http://jsfiddle.net/aAbJY/1/

提交回复
热议问题