4种js原生修改css样式的方法

html

    <p id = "target"> rainbow p>
复制代码

1. Inline styles

document.getElementById('target').style.color = 'tomato'
复制代码

2. Global styles

var style = document.createElement('style');
style.innerHTML = '
    #target {
     color: blueviolet;
    }
';
document.head.appendChile(style);
复制代码

3.CSSOM inserRule

    var style = document.createElement('style');
    document.head.appendChild(style);
    style.sheet.inserRule('#target {color: darkseagreen}')
复制代码

4. Constructable Stylesheets

// Create our shared stylesheet
const sheet = new CSSStyleSheet();
sheet.replaceSync('#target {color: darkseagreen}');

// Apply the stylesheet to a document
document.adoptedStyleSheets = [sheet];
复制代码

你可能感兴趣的:(4种js原生修改css样式的方法)