2017-10-03 13 views
1

私は、header :: before擬似要素の背景色を動的に変更する方法を検討しています。しかし、別のクラスを作成せずに2回目の他のすべての属性を定義しなくても、バックグラウンドカラーを変更して、異なる属性の1つだけを切り替えることもできます。それは可能なのか、もしそうなら、どんな提案ですか?css - 動的に擬似要素の背景を変更する

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); 

答えて

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>

+0

答えのためのTyのようなビットは、私が探していただけで何:) –