Get CSS properties values for a not yet applied class

后端 未结 2 817
再見小時候
再見小時候 2021-01-18 03:18

In jQuery, I can get a CSS property value for a selector using the css method and passing a property name, for example:

$(\'#myElement\').css(\'backgr

相关标签:
2条回答
  • 2021-01-18 03:26

    Short answer: You cannot get a css property from a class that is not applied to any element. However, you can directly read it from a CSS stylesheet and you can do this by using DOM CSS

    And then maybe have something like:

    var bgimage = myStyleSheet.cssRules[0].style.background-image;
    
    0 讨论(0)
  • 2021-01-18 03:30

    You can create a temporary element without adding it to the DOM, and inspect the relevant property. CSS will apply, even if the element is not added to the DOM. E.g.

    CSS

    p { color: red; }
    

    JS

    var p = document.createElement('p');
    alert(window.getComputedStyle(p, null).getPropertyValue('color'));
    

    will give you the color value, but not add anything to the DOM.

    WARNING

    After a bit of research, I've determined that this method only works in Gecko-based browsers, so is not suitable for general-purpose use. This situation may change in future, but I wouldn't rely on this if you want a cross-browser solution today.

    Given that, I would suggest you just create a temporary element, add the desired class, add it to the document, inspect it to get the style value, then remove it. You can additionally apply styles such as display: none to prevent it from being shown to the user during the incredibly brief time that it's part of the document.

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