简体   繁体   中英

Can I search and replace colours in a CSS file when a page loads?

What I want to do is search for all instances of a particular colour within a CSS document, identified by its hex value, and replace all those instances with a new hex value. Then, after the colours have been changed, the CSS is applied to the page.

Really, a CSS document is just a text file, so surely there's a way to catch it before it is served to the browser and do some text based search and replace. Look for a particular HEX code and replace all instances with another.

How could that be done?

You can do the following:

function changeColor(oldColor, newColor) {
   var all = document.getElementsByTagName('*');

   Array.prototype.forEach.call(all, function(element){
     if (element.style.background === oldColor) {
       element.style.background = newColor;
     }
   })  
}

This way you're looping over each element on the page, checking if it has the old color, and then if so, changing it to the new color.

First there are some errors in your code.

I have creaeted a JSFIDDLE

    function changeColor(color) {
   var a =  document.getElementById('coloredThing');
   a.style.background = color;
}

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