【问题标题】:css - dynamically change background of pseudo elementcss - 动态改变伪元素的背景
【发布时间】:2017-10-03 08:19:32
【问题描述】:

我正在研究动态更改 header::before 伪元素的背景颜色。但我也想只更改背景颜色,而不必创建另一个类并第二次定义所有其他属性,以便仅针对一个不同的属性在它们之间切换。有没有可能,如果有,有什么建议吗?

HTML:

<html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
        <header></header>
    </body>
    <script src="code.js"></script>
</html>

CSS:

header {
position: absolute;
width: 100%;
height: 600px;
box-shadow: 0 0 10px black;
}

header::before {
content: "";
z-index: -1;
position: absolute;
width: inherit;
height: inherit;
background-color: red;

/*
few more attributes
*/
}

JS:

setInterval(function(){
var random = Math.floor((Math.random() * 5) + 1);

if(random == 1) console.log(1);// and also set header::before with background-color: blue;
else if(random == 2) console.log(2);// and also set header::before with background-color: green;
else console.log(3);// and also set header::before with background-color: red;
}, 2000);

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:

    使用标题类,您可以为 header.red::before 等创建 css,然后根据需要更改标题类? - 有点像

    var hdr = document.querySelector('header');
    setInterval(function() {
        var random = Math.floor((Math.random() * 5) + 1);
    
        if (random == 1) hdr.className = 'blue'; // and also set header::before with background-color: blue;
        else if (random == 2) hdr.className = 'green'; // and also set header::before with background-color: green;
        else hdr.className = 'red'; // and also set header::before with background-color: red;
    }, 2000);
    header {
        position: absolute;
        width: 100%;
        height: 600px;
        box-shadow: 0 0 10px black;
    }
    
    header::before {
        content: "";
        z-index: -1;
        position: absolute;
        width: inherit;
        height: inherit;
        background-color: red;
        /*
    few more attributes
    */
    }
    
    header.red::before {
        background-color: red;
    }
    header.blue::before {
        background-color: blue;
    }
    header.green::before {
        background-color: green;
    }
    &lt;header&gt;&lt;/header&gt;

    【讨论】:

    • 回答问题,正是我想要的:)
    猜你喜欢
    • 1970-01-01
    • 2021-10-23
    • 2022-10-07
    • 1970-01-01
    • 2014-03-12
    • 2021-10-01
    • 2021-08-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多