Find all CSS rules that apply to an element

后端 未结 9 912
温柔的废话
温柔的废话 2020-11-22 10:26

Many tools/APIs provide ways of selecting elements of specific classes or IDs. There\'s also possible to inspect the raw stylesheets loaded by the browser.

However,

9条回答
  •  独厮守ぢ
    2020-11-22 11:06

    Ensuring IE9+, I wrote a function which calculates CSS for requested element and its children, and gives possibility to save it to a new className if needed in snippet below.

    /**
      * @function getElementStyles
      *
      * Computes all CSS for requested HTMLElement and its child nodes and applies to dummy class
      *
      * @param {HTMLElement} element
      * @param {string} className (optional)
      * @param {string} extras (optional)
      * @return {string} CSS Styles
      */
    function getElementStyles(element, className, addOnCSS) {
      if (element.nodeType !== 1) {
        return;
      }
      var styles = '';
      var children = element.getElementsByTagName('*');
      className = className || '.' + element.className.replace(/^| /g, '.');
      addOnCSS = addOnCSS || '';
      styles += className + '{' + (window.getComputedStyle(element, null).cssText + addOnCSS) + '}';
      for (var j = 0; j < children.length; j++) {
        if (children[j].className) {
          var childClassName = '.' + children[j].className.replace(/^| /g, '.');
          styles += ' ' + className + '>' + childClassName +
            '{' + window.getComputedStyle(children[j], null).cssText + '}';
        }
      }
      return styles;
    }
    

    Usage

    getElementStyles(document.getElementByClassName('.my-class'), '.dummy-class', 'width:100%;opaity:0.5;transform:scale(1.5);');
    

提交回复
热议问题