简体   繁体   中英

How modify a property of external CSS file using jQuery / Javascript

I want to change a property of external CSS file using javascript/jquery

Example; in the of the web page I'm using:

<!-- Star rating -->
<link href="css/star-rating.min.css" rel="stylesheet" />

And I want to access and change the color of specific style (Found in the external CSS):

CSS

Exists a method using JavaScript or jQuery to do that?

I create a js method to achieve this:

function getStyleSheet(cssName, rule) {
    for (i = 0; i < document.styleSheets.length; i++) {
        if (document.styleSheets[i].href.toString().indexOf(cssName) != -1)
            for (x = 0; x < document.styleSheets[i].rules.length; x++) {
                if (document.styleSheets[i].rules[x].selectorText.toString().indexOf(rule) != -1)
                    return document.styleSheets[i].rules[x];
            }

    }

    return null;
}

To change any property only is required the following:

getStyleSheet('star-rating', '.rating-container .rating-stars').style.color = "#AFAFAF";

Ok, let's analyze this....

You want to change a CSS rule on your code. I asume you want to do it as a response to something that happens in the browser...

Change physically the line in the CSS file is not impossible, but I supose that it isn't what you are looking for.

The best option, probably would be to change the CSS style through javascript as a reaction to the event or situation that makes you want to change the style. Using jquery:

$(".rating-container").css("color", "#f0f");

As an alternative, use different CSS classes for different element states and just change classes into your js code:

$("#myAffectedElement").removeClass("oldColorClass");
$("#myAffectedElement").addClass("newColorClass");

This will allow you to modify directly individual elements styles instead of changing every originally classed element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM