If using Javascript only, I would suggest the following:
Rename background files with names with sequential numbers:
fundo1.jpg
fundo2.jpg
fundo3.jpg
fundo4.jpg
Then after your header
, call the script:
<script>
var fundo = [1,2,3,4][Math.floor(Math.random()*4)];
var e_header = document.querySelector("header");
e_header.style.backgroundImage = "url(fundo"+fundo+".jpg)";
</script>
Obs.: Since the images will be called by random numbers, it may be that the same image is loaded after a new page load. Should this be avoided great importance, you can create a localStorage
to prevent the same image from being loaded again at the next page load. To do this the code changes:
<script>
function randFundo(){
var fundo = [1,2,3][Math.floor(Math.random()*3)];
!localStorage.fundo ? localStorage.fundo = fundo : 0;
return localStorage.fundo == fundo
?
(localStorage.fundo = fundo+1)
:
(localStorage.fundo = fundo);
}
var e_header = document.querySelector("header");
e_header.style.backgroundImage = "url(fundo"+randFundo()+".jpg)";
</script>
SIMULATION
Code only for testing without refresh on the page. Use one of the codes
above.
In the example below, click the button Upgrade to exchange the fund of div
:
var localstorage = { fundo: "" };
function atualizar(){
var e_header = document.querySelector("header");
e_header.style.backgroundImage = "url(http://dvdteste.hospedagemdesites.ws/imagem"+randFundo()+".jpg)";
}
function randFundo(){
var fundo = [1,2,3][Math.floor(Math.random()*3)];
!localstorage.fundo ? localstorage.fundo = fundo : 0;
return localstorage.fundo == fundo
?
(localstorage.fundo = fundo+1)
:
(localstorage.fundo = fundo);
}
window.onload = atualizar;
header{
display: block;
width: 300px;
height: 200px;
background-color: yellow;
background-size: cover;
float: left;
}
<header></header>
<input type="button" value="Atualizar" onclick="atualizar()" />
But I don’t understand, I add the images where? Generally I would in the file
estilo.css
and would put a background-image but in this case where I would show the way to the images?– Clayton Furlanetto
@Claytonfurlanetto That’s right. To do this in the CSS file would be more complicated as it would have to create a class for each background image. At my suggestion, you just put the path of the images in
"url(fundo"+randFundo()+".jpg)";
.– Sam
@Claytonfurlanetto Would be like this:
"url(CAMINHO_DAS_IMAGENS/NOME"+randFundo()+".jpg)";
– Sam
@Claytonfurlanetto Whereas the images are in the same directory. Let’s assume that the images are in the "/images" folder, then you would put
"url(imagens/fundo"+randFundo()+".jpg)";
– Sam
gave right face, worked perfectly, this was what I wanted msm, thank you again!
– Clayton Furlanetto