How to get CSS class property in Javascript?

前端 未结 4 1961
挽巷
挽巷 2020-12-14 06:41
.test {
    width:80px;
    height:50px;
    background-color:#808080;
    margin:20px;
}

HTML -

Click H
4条回答
  •  感情败类
    2020-12-14 07:04

    The accepted answer is the best way to get the computed values. I personally needed the pre-computed value. Say for instance 'height' being set to a 'calc()' value. I wrote the following jQuery function to access the value from the style sheet. This script handles nested 'media' and 'supports' queries, CORS errors, and should provide the final cascaded precomputed value for accessible properties.

    $.fn.cssStyle = function() {
    		var sheets = document.styleSheets, ret = [];
    		var el = this.get(0);
    		var q = function(rules){
    			for (var r in rules) {
    				var rule = rules[r];
    				if(rule instanceof CSSMediaRule && window.matchMedia(rule.conditionText).matches){
    					ret.concat(q(rule.rules || rule.cssRules));
    				} else if(rule instanceof CSSSupportsRule){
    					try{
    						if(CSS.supports(rule.conditionText)){
    							ret.concat(q(rule.rules || rule.cssRules));
    						}
    					} catch (e) {
    						console.error(e);
    					}
    				} else if(rule instanceof CSSStyleRule){
    					try{
    						if(el.matches(rule.selectorText)){
    							ret.push(rule.style);
    						}
    					} catch(e){
    						console.error(e);
    					}
    				}
    			}
    		};
    		for (var i in sheets) {
    			try{
    				q(sheets[i].rules || sheets[i].cssRules);
    			} catch(e){
    				console.error(e);
    			}
    		}
    		return ret.pop();
    	};
      
      // Your element
      console.log($('body').cssStyle().height);

提交回复
热议问题