Home >Web Front-end >CSS Tutorial >How Can I Efficiently Retrieve CSS Style Attributes from Classes Using JavaScript?
Retrieving Style Attributes from CSS Classes Using JavaScript/jQuery
When working with style animations in JavaScript, it can be necessary to access properties defined in CSS classes. The challenge arises when needing to dynamically update the animation based on CSS changes, ensuring it remains consistent.
One approach involves using a hidden element assigned to the target CSS class, extracting its computed color, and then utilizing it in the animation. However, this method is generally considered inefficient.
A more robust solution is to traverse the stylesheets associated with the document and search for the specific selector and style property in question. Here's an implementation of a function that performs this task:
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]); // searches a specific stylesheet
This function relies on the ability to split a comma-separated list of selectors and check if the given selector is part of the list. It supports both grouped rules and external stylesheets from the same domain.
By utilizing this function, you can dynamically adjust style animations based on CSS class property changes, ensuring that your website or application remains aesthetically consistent and responsive to user preferences.
The above is the detailed content of How Can I Efficiently Retrieve CSS Style Attributes from Classes Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!