Hola, quiero desvanecerme en una nueva imagen de fondo digamos cada 60 segundos. He configurado la imagen de fondo de esta manera:
body {background-image: url(background.jpg);}
Ahora quiero cambiarlo, así que después de 60 segundos cambia a background2.jpg, luego después de 60 segundos a background3.jpg y así sucesivamente ..
He encontrado muchas cosas sin cambiarlas en el cuerpo pero solo como una imagen … ¿alguna solución rápida?
¡Gracias!
Cambios:
Tomó la carne de este código de esta respuesta anterior y agregó un poco de bling (usando mi fondo de sitio stash lol)
violín original 🙂
Javascript:
$(document).ready(function () { var img_array = [1, 2, 3, 4, 5], newIndex = 0, index = 0, interval = 5000; (function changeBg() { // -------------------------- // For random image rotation: // -------------------------- // newIndex = Math.floor(Math.random() * 10) % img_array.length; // index = (newIndex === index) ? newIndex -1 : newIndex; // ------------------------------ // For sequential image rotation: // ------------------------------ index = (index + 1) % img_array.length; $('body').css('backgroundImage', function () { $('#fullPage').animate({ backgroundColor: 'transparent' }, 1000, function () { setTimeout(function () { $('#fullPage').animate({ backgroundColor: 'rgb(255,255,255)' }, 1000); }, 3000); }); return 'url(http://www.fleeceitout.com/images/field.' + img_array[index] + '.jpg)'; }); setTimeout(changeBg, interval); })(); });
CSS:
body { height: 100%; width: 100%; margin: 0; padding: 0; position: relative; background-image: url(http://www.fleeceitout.com/images/field.2.jpg); background-size: cover; background-repeat: no-repeat; background-position: 0 0; background-attachment: fixed; } #fullPage { position: absolute; min-width: 100%; min-height: 100%; top: 0; left: 0; background-color: rgb(255, 255, 255); }
Puede usar el método setInterval
y cambiar entre las clases definidas en su CSS que tienen diferentes imágenes de fondo:
setInterval(function() { var $body = $('body'); if($body.hasClass('background1')) { $body.removeClass('background1'); $body.addClass('background2'); } else { $body.removeClass('background2'); $body.addClass('background1'); } }, 1000);
Violín
Este ejemplo usa un intervalo de 1000
que es un segundo. Puede cambiar este valor por el período de tiempo que esté buscando.
ACTUALIZAR
Noté que tu pregunta pedía un fundido, así que agregué una propiedad CSS3 en el cuerpo:
body { transition: background 0.5s linear; }
El violín ha sido actualizado.
Basándose en la respuesta de Dan-Nolan (anteriormente usuario506980), también puede asignar los fondos a una matriz y luego llamar a cada fondo de la matriz con un contador
jsFiddle Demo
Además, puede asignar la función setInterval a una variable, y luego usar esa variable más adelante para detener las repeticiones.
$(document).ready(function() { var cnt=0, bg; var $body = $('body'); var arr = ['bg1.jpg','bg2.jpg','bg3.jpg','bg4.jpg','bg5.jpg','bg6.jpg']; var bgrotater = setInterval(function() { if (cnt==5) cnt=0; bg = 'url("' + arr[cnt] + '")'; cnt++; $body.css('background-image', bg); }, 1000); //To stop the backgrounds from rotating. Note the critical step above //of assigning the setInterval function to a variable, in order to //use it again (below) to stop the repeating function $('#some_button_id').click(function() { clearInterval(bgrotater); }); }); //END document.ready
Ya que construí sobre la respuesta de Dan-Nolan, por favor devuélvame su respuesta si usted votó a favor de esta. Y veo que Deryck ha agregado el suyo, y también es correcto. Upvote.
https://github.com/srobbin/jquery-backstretch Backstretch es un plugin jQuery simple que le permite agregar una imagen de fondo con capacidad de presentación de diapositivas y de tamaño dynamic a cualquier página o elemento. La imagen se estirará para ajustarse a la página / elemento y cambiará de tamaño automáticamente a medida que cambie el tamaño de la ventana / elemento.
jQuery(document).ready(function() { var cnt=0, bg; var $body = jQuery('body'); var arr = ['secondbg.jpg','sartulebis-archeva2.png']; animate = function(){ } var bgrotater = setInterval(function() { if (cnt==2) cnt=0; bg = 'url("http://yalcingroup.ge/test/wp-content/uploads/2015/08/' + arr[cnt] + '")'; cnt++; jQuery('#background_cycler').animate({opacity:1}, 2000, function(){ $body.css('background-image', bg); }); jQuery('#background_cycler').animate({opacity:0}, 2000); },10000);
});
Cada 12 segundos se cambia una imagen en el contenedor de presentación; puede ser una etiqueta corporal
HTML
JS
delay (11000) + setTimeout (1000) = 12 segundos de duración de la transición = 300 + 300 = 600 mseg
var imgArray = ['image-1', 'image-2', 'image-3'], index = 0; (function changeBG(){ // mask element only for transition $('.mask').delay(11000).animate({opacity:1}, 300, function(){ index = (index + 1) % img_array.length; // in presentacion element change bg images $('.presentacion').css("background-image", "url('images/bg-"+imgArray[index]+".jpg')"); }).animate({opacity: 0}, 300); setTimeout(changeBG, 1000); })();
CSS
.presentacion { background-attachment: fixed; background-color: rgba(0, 0, 0, 0.5); background-image: url("images/image-1.jpg"); background-position: center center; background-repeat: no-repeat; -webkit-background-size: cover; background-size: cover; position: relative; width: 100%; z-index: 0; opacity: 1; } .mask { background-color: rgba(0,0,0,0); bottom: 0; left: 0; opacity: 0; position: absolute; right: 0; top: 0; height: 100%; z-index: 10; }
Basándose en la respuesta de Deryck …
Si jQuery Color no funciona correctamente (que a veces lo hace), puede usar fadeIn()
y fadeOut()
lugar:
$(document).ready(function () { var img_array = [1, 2, 3, 4, 5], newIndex = 0, index = 0, interval = 5000; (function changeBg() { // -------------------------- // For random image rotation: // -------------------------- // newIndex = Math.floor(Math.random() * 10) % img_array.length; // index = (newIndex === index) ? newIndex -1 : newIndex; // ------------------------------ // For sequential image rotation: // ------------------------------ index = (index + 1) % img_array.length; $('body').css('backgroundImage', function () { $('#fullPage').fadeOut(1000, function () { setTimeout(function () { $('#fullPage').fadeIn(1000); }, 3000); }); return 'url(http://www.fleeceitout.com/images/field.' + img_array[index] + '.jpg)'; }); setTimeout(changeBg, interval); })(); });