我正在考虑在伪元素之前动态更改header ::的背景颜色。但是我也想改变背景颜色,而不必创建另一个类,并且第二次定义所有其他属性,仅在一个属性不同的情况下在它们之间切换。是否有可能,如果有的话,有什么建议吗?
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);
答案 0 :(得分: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;
}
<header></header>