gpt4 book ai didi

javascript - css - 动态改变伪元素的背景

转载 作者:行者123 更新时间:2023-11-30 15:00:58 25 4
gpt4 key购买 nike

我正在研究动态更改 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);

最佳答案

在标题上使用类,您可以为 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;
}
<header></header>

关于javascript - css - 动态改变伪元素的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46535395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com