Reading non-inline CSS style info from Javascript

前端 未结 4 995
栀梦
栀梦 2020-12-03 09:16

I know I must be missing something here, but I cannot seem to get this to work.

I have assigned a background color to the body of an html document using the style ta

相关标签:
4条回答
  • 2020-12-03 09:43

    The style property of a DOM element refers only to the element's inline styles.

    Depending on the browser, you can get the actual style of an element using DOM CSS

    In firefox, for example:

    var body = document.getElementsByTagName("body")[0];
    var bg = window.getComputedStyle(body, null).backgroundColor;
    

    Or in IE:

    var body = document.getElementsByTagName("body")[0];
    var bg = body.currentStyle.backgroundColor;
    
    0 讨论(0)
  • 2020-12-03 10:01

    In this case, you'll want the computedStyle on the Element as the style attribute hasn't been set yet. In IE, you'll need to check the Element's currentStyle property, via something like this.

    0 讨论(0)
  • 2020-12-03 10:06

    Here is a function you can use (without the use of a framework ie) that was posted here by InsDel:

    function getStyle(className) {
        var classes = document.styleSheets[0].rules || document.styleSheets[0].cssRules
        for(var x=0;x<classes.length;x++) {
            if(classes[x].selectorText==className) {
                    (classes[x].cssText) ? alert(classes[x].cssText) : alert(classes[x].style.cssText);
            }
        }
    }
    getStyle('.test')
    
    0 讨论(0)
  • 2020-12-03 10:07

    That's just how css works. There's no straight-forward way to get the computed css attributes of an element within Javascript, that I know of, short of browser specific utilities.

    0 讨论(0)
提交回复
热议问题