Home > Web Front-end > CSS Tutorial > How Can I Access CSS Class Style Attributes Using JavaScript or jQuery?

How Can I Access CSS Class Style Attributes Using JavaScript or jQuery?

Barbara Streisand
Release: 2024-12-09 06:08:14
Original
1042 people have browsed it

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;
}
Copy after login

For example, to get the color attribute of the .highlight class:

var color = getStyleRuleValue('color', '.highlight');
Copy after login

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);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template