2017-10-03 1 views
1

Ich schaue auf dynamisch wechselnde Hintergrundfarbe von Header :: vor Pseudo-Element. Aber ich möchte auch nur die Hintergrundfarbe ändern, ohne eine andere Klasse zu erstellen und alle anderen Attribute zum zweiten Mal zu definieren, um zwischen ihnen nur für ein anderes Attribut zu wechseln. Ist es möglich und wenn ja, irgendwelche Vorschläge?CSS - dynamisch Hintergrund des Pseudo-Elements ändern

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

Antwort

1

Klassen auf Header verwenden, können Sie CSS für header.red::before etc schaffen könnte, dann Ändern Sie die Header-Klasse wie erforderlich? - ein bisschen wie

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 für Antwort, genau das, was ich gesucht habe :) –