简体   繁体   中英

How to rotate programmatically the background image of a div that uses background-size:cover with Jquery?

I've tried this in order to change the background image for a website but unfortunately it isn't working. Sadly, the console doesn't give me any clue as to what's wrong. So I've ran out of ideas. Wish someone can help. What I'm trying to do is to rotate the images on the background of the website based on an array of images. I don't have a clue as to why it isn't working (perhaps the cover property of the background is getting in the way?). I've been hours working on this and changing the code so that it might work. First I did it without populating an array with new Image() constructor, then I thought that should fix it, because otherwise the browser may not have a dom node to work with. But I'm still stuck. (Most of the code is based on an answer in this very website, here Here's the code:

$(document).ready(function() {
fondos = new Array('/Foto_Pimend/activos/flickr_foto_fondo_1.jpg',     '/Foto_Pimend/activos/flickr_foto_fondo_2.jpg',     '/Foto_Pimend/activos/flickr_foto_fondo_3.jpg');
cargar_fondos=new Array();
fondo_num = 1;
var i;
for(i=0; i<fondos.length; i++) {
cargar_fondos[i]=new Image();
cargar_fondos[i].src=fondos[i]; 
}
function rotarFondos() {
$('.fondo_intro').css({'background':'url("'+cargar_fondos[fondo_num++     %cargar_fondos.length].src+'") no-repeat 50% 100% cover'},'slow');
}
intId=setTimeout(rotarFondos, 10000);
});

The div I'm trying to change programmatically has this style:

.fondo_intro {background: url(/Foto_Pimend/activos/flickr_foto_fondo_1.jpg) no-repeat;     width:100%; background-size:cover; background-position:50% 100%;position:fixed;     height:100%;}

I also tried linking the function to a click event that I use to change the content, like so:

$('.link_manejador').click(function() {
var content = $(this).attr('name')+'_template';
llamada_contenido(content); rotarFondos();  
});

That way instead of a rotating background I'd have a changing background depending on content. But it doesn't work either, what's more frustrating, the console doesn't show any error or hint as to what's happening. I can see the images being created and the counter (namely fondo_num) incrementing, but nothing happens. Even more to it: when I issue on the console:

$('.fondo_intro').css({'background-  image':'url(/Foto_Pimend/activos/flickr_foto_fondo_2.jpg'},'slow')

Nothing happens. So I'm not understanding something, very clearly.

Remove "cover" from this line of code:

$('.fondo_intro').css({'background':'url("'+cargar_fondos[fondo_num++ %cargar_fondos.length].src+'") no-repeat 50% 100% cover '},'slow');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM