Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
87 views
in Technique[技术] by (71.8m points)

How to get a style attribute from a CSS class by javascript/jQuery?

How can I access a property from a CSS class by jQuery? I have a CSS class like:

.highlight { 
    color: red; 
}

And I need to do a color animation on an object:

$(this).animate({
    color: [color of highlight class]
}, 750);

So that I can change from red to blue (in the CSS) and my animation will work in accordance with my CSS.

One approach would be to place an invisible element with the highlight class and then get the color of the element to use in the animation, but I guess this is a very, very bad practice.

Any suggestions?

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I wrote a small function that traverses the stylesheets on the document looking for the matched selector, then style.

There is one caveat, this will only work for style sheets defined with a style tag, or external sheets from the same domain.

If the sheet is known you can pass it in and save yourself from having to look in multiple sheets (faster and if you have colliding rules it's more exact).

I only tested on jsFiddle with some weak test cases, let me know if this works for you.

function getStyleRuleValue(style, selector, sheet) {
    var sheets = typeof sheet !== 'undefined' ? [sheet] : document.styleSheets;
    for (var i = 0, l = sheets.length; i < l; i++) {
        var sheet = sheets[i];
        if( !sheet.cssRules ) { continue; }
        for (var j = 0, k = sheet.cssRules.length; j < k; j++) {
            var rule = sheet.cssRules[j];
            if (rule.selectorText && rule.selectorText.split(',').indexOf(selector) !== -1) {
                return rule.style[style];
            }
        }
    }
    return null;
}

example usage:

var color = getStyleRuleValue('color', '.foo'); // searches all sheets for the first .foo rule and returns the set color style.

var color = getStyleRuleValue('color', '.foo', document.styleSheets[2]); 

edit:

I neglected to take into consideration grouped rules. I changed the selector check to this:

if (rule.selectorText.split(',').indexOf(selector) !== -1) {

now it will check if any of the selectors in a grouped rules matches.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...