Get a CSS value with JavaScript

前端 未结 9 1432
温柔的废话
温柔的废话 2020-11-21 07:55

I know I can set a CSS value through JavaScript such as:

document.getElementById(\'image_1\').style.top = \'100px\';

But, can I

9条回答
  •  借酒劲吻你
    2020-11-21 08:13

    The cross-browser solution without DOM manipulation given above does not work because it gives the first matching rule, not the last. The last matching rule is the one which applies. Here is a working version:

    function getStyleRuleValue(style, selector) {
      let value = null;
      for (let i = 0; i < document.styleSheets.length; i++) {
        const mysheet = document.styleSheets[i];
        const myrules = mysheet.cssRules ? mysheet.cssRules : mysheet.rules;
        for (let j = 0; j < myrules.length; j++) {
          if (myrules[j].selectorText && 
              myrules[j].selectorText.toLowerCase() === selector) {
            value =  myrules[j].style[style];
          }
        }
      }
      return value;
    }  
    

    However, this simple search will not work in case of complex selectors.

提交回复
热议问题