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

前端 未结 4 1027
南方客
南方客 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条回答
  •  旧时难觅i
    2021-01-19 15:24

    For two reasons:

    1. getElementsByTagName() returns a list of elements, not a single element as getElementById(). Thus, you need to subscript the resulting NodeList to get the required DOM element;
    2. Most importantly, when you access the styles through the style property of the element, you'll only get the inline styles, not the ones that you assign through a CSS class.

    To get the computed styles, you could use window.getComputedStyle(), which will give you the final used values of all the CSS properties of the element:

    alert(window.getComputedStyle(title).opacity);
    

    DEMO.

    Unfortunately, getComputedStyle is not available in IE < 9, but you can easily find a polyfill, such as this one.

提交回复
热议问题