简体   繁体   中英

Getting CSS styles that are set in a style sheet with native Javascript

I'm having a couple issues where I need to get the styles of an element with native JS (Not JQ). However, using something like elem.style.property returns "" because the actual HTML element doesn't have it set on it.

To make things more specific, one thing I need to get is the display value of an element, but elem.style.display gives "", but I need to know "block" or "none"

I understand WHY that's happening; I just need to know the proper way to get that value with native JS.

Thanks.

Unless you have set the style directly on the element itself within your HTML you need to use either currentStyle or getComputedStyle eg:

function getStyle(el,styleProp)
{
    if (el.currentStyle)
        return el.currentStyle[styleProp];

    return document.defaultView.getComputedStyle(el,null)[styleProp];
}

So for your purposes, you can call:

getStyle(element, 'visibility');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM