纯CSS 动态修改主题色

133 阅读1分钟

css

body{
        --themeColor:orange;
        --fThemeColoe: #fff;
}
.box{
        overflow: hidden; border: 1px solid #333; padding: 20px;
}
.box div{
        float: left;
        width: 100px;
        height: 100px;
        margin-right: 10px;;
}
.box div:nth-child(1){
        background: red;
}
.box div:nth-child(2){
        background: blue;
}
.box div:nth-child(3){
        background: yellow;
}
.box div:nth-child(4){
        background: pink;
}
p{
        width: 300px;
        height: 300px;
        background: var(--themeColor);
        color: var(--fThemeColoe);
        font-size: 20px;
        text-align: center;
        line-height: 300px;
}

HTML

<div class="box" >
        <div color="red" fcolor="green"></div>
        <div color="blue" fcolor="yellow"></div>
        <div color="yellow" fcolor="#333"></div>
        <div color="pink" fcolor="blueviolet"></div>
</div>

<p id="setColor">测试</p>

js

window.onload = function(){
        var ele = document.querySelectorAll('.box div');
        for(var i = 0; i < ele.length; i++){
                ele[i].onclick = function(){
                        document.getElementById('setColor').style.setProperty('--themeColor', this.getAttribute('color'));
                        document.getElementById('setColor').style.setProperty('--fThemeColoe', this.getAttribute('fcolor'));

                }
        }
}
            `