Estoy tratando de hacer que la imagen de fondo de mi sitio web cambie cada cierta cantidad de segundos, he intentado hacer esto con esto:
var images = new Array( 'Space.gif', 'Windows.gif', ); var slider = setInterval(function() { document.getElementsByClassName('bg-img')[0].setAttribute('style', 'background-image: url("'+images[0]+'")'); images.splice(images.length, 0, images[0]); images.splice(0, 1); }, 10000); body { background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: 100%; } <div class="bg-img" style="background-image: url('space.gif'),background-image: url('windows.gif');"> <div class="overlay"></div> </div>Y también he probado con este código de JavaScript:
function changeBg(){ const images = [ 'url("Space.gif")', 'url("Windows.gif")', ] const selection = document.querySelector('selection') const bg = images[Math.floor(Math.random()* images.length)]; selection.style.backgroundImage = bg; } setInterval(changeBg, 1000000)Pero nada funciona :(
En su CSS, está preparando el <body> para una imagen de fondo:
body { background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: 100%; } Pero está agregando la imagen a un elemento con la clase "bg-img" en lugar de <body> :
document.getElementsByClassName('bg-img')... Puede (1) agregar la imagen al <body> o (2) hacer que el <div> cubra la pantalla completa:
1) Establecer la imagen en el elemento <body> :
La propiedad
Document.bodyrepresenta el nodo<body>... del documento actual, onullsi no existe dicho elemento.
var images = new Array( 'https://fakeimg.pl/200x150/282868/eae0d0/', 'https://fakeimg.pl/200x150/682828/eae0d0/' ); var slider = setInterval(function() { document.body.setAttribute('style', 'background-image: url("' + images[0] + '")'); images.splice(images.length, 0, images[0]); images.splice(0, 1); }, 2000); body { background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: 100%; background-image: url('https://fakeimg.pl/200x150/282828/eae0d0/'); } 2) O haz el <div> a pantalla completa:
Dado que <div> no tiene contenido ni ancho ni alto , no se mostrará en la página. Puede usar CSS para hacer que el elemento cubra la ventana del navegador .
var images = new Array( 'https://fakeimg.pl/200x150/282868/eae0d0/', 'https://fakeimg.pl/200x150/682828/eae0d0/' ); var slider = setInterval(function() { document.getElementsByClassName('bg-img')[0].setAttribute('style', 'background-image: url("' + images[0] + '")'); images.splice(images.length, 0, images[0]); images.splice(0, 1); }, 2000); .bg-img { position: fixed; width: 100vw; height: 100vh; background-repeat: no-repeat; background-attachment: fixed; background-position: center; background-size: 100%; background-image: url('https://fakeimg.pl/200x150/282828/eae0d0/'); } <div class="bg-img"></div>