简体   繁体   中英

change all occurrences of a word in css using javascript

I've seen we can change all occurrences of text in HTML using javascript using document.body.innerHTML = document.body.innerHTML.replace(/hello/g, 'hi'); but i'm trying to change all occurences inside the CSS file.

What I'm trying to do is something like that:

var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var proportion = w/h;
if (proportion > 1.59) {
    // width > height
    document.body.innerHTML = document.body.innerCSS(?).replace(/vw/g, 'vh');
} else {
    // height > width
    document.body.innerHTML = document.body.style(?).replace(/vh/g, 'vw');

}

Like changing vw to vh when the width of the page is bigger, and vh to vw when height is bigger.

You can modify the stylesheet rule selectors via javascript:

Fiddle

function replace_css_selector(search_value, new_value) {
    var css_styles = "";
    var style = null;
    for (var i = 0; i < document.styleSheets.length; i++) {
        with(document.styleSheets[i]) {
            if (typeof css_rules != "undefined") {
                style = css_rules;
            } else if (typeof rules != "undefined") {
                style = rules;
            }
        }
        for (var item in style) {
            if (style[item].cssText != undefined) {
                css_styles = (style[item].cssText);
                style[item].selectorText = style[item].selectorText.replace(search_value, new_value);
            }

        }
    }
    return style;
}

list = replace_css_selector(/vh/g, 'vw');

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