Home >Web Front-end >CSS Tutorial >How Can I Access CSS Class Style Attributes Using JavaScript or jQuery?
Access CSS Class Style Attribute using JavaScript/jQuery
When dealing with CSS animation, it can be challenging to access the style attributes of elements from a CSS class using JavaScript or jQuery. However, there are efficient ways to retrieve these attributes.
Retrieving Style Attribute Using Custom Function
One approach is to create a custom JavaScript function that traverses the document's style sheets looking for the matching CSS selector and style. Here's a sample function:
function getStyleRuleValue(style, selector, sheet) { var sheets = sheet ? [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; }
For example, to get the color attribute of the .highlight class:
var color = getStyleRuleValue('color', '.highlight');
Note: This function assumes that the style sheets are defined inline or have the same domain as the current document.
Applying Animation
With the retrieved style attribute, you can apply it to your animation:
$(this).animate({ color: color // Retrieved color attribute }, 750);
By updating the CSS class from red to blue, the animation will adjust accordingly, aligning with the updated CSS color style.
The above is the detailed content of How Can I Access CSS Class Style Attributes Using JavaScript or jQuery?. For more information, please follow other related articles on the PHP Chinese website!