简体   繁体   中英

Using jQuery to fade in a new image

Below is the image element that is acting as the background. The position is absolute and it also has a low z-index so it stays behind the rest of the content.

<img src="day-sky.jpg" id="background" />

The secs below just refers to seconds in a minute. This is just for test purposes, but I'd like to have one background image if the seconds is < 30 and a different one if it's greater that 30. If possible the transition would be a nice fade to the next image.

I've been searching around for ways to do this but haven't come up with a good way to do it. Any thoughts?

function changeBackground() {

if (secs > 30) {
    //have one background
}
else {
    //have a different background
  }
}

You might want to use setInterval() function to change the background after every time stamp you define as per your requirement.

setInterval(changebackground, timeout); runs the code/function once after the timeout.

 $(function() {
    setInterval(function() {
        var bg = ["#000","#FF0", "#909"]
        var rep= Math.floor(Math.random() *3);
                $("body").css("background",bg[rep])
    }, 3000)
  })

Here's a working example: http://jsfiddle.net/PKqGk/

var imgs = [
        "http://placehold.it/1920x1080/&text=1",
        "http://placehold.it/1920x1080/&text=2",
        "http://placehold.it/1920x1080/&text=3",
        "http://placehold.it/1920x1080/&text=4",
        "http://placehold.it/1920x1080/&text=5",    
        "http://placehold.it/1920x1080/&text=6"   
    ],
    ind = 0,
    dur = 10 * 1000; // ten seconds
(function imgSlide(){

    var img = ind % 2 ? $('#imageOne') : $('#imageTwo'),
        hid = ind % 2 ? $('#imageTwo') : $('#imageOne');

    console.log(img, hid);

    img.fadeOut("slow", function(){
        hid.fadeIn("slow").css('margin-left', -hid.width()/2);
        if (++ind == imgs.length) ind = 0;
        img.attr('src', imgs[ind]);
        setTimeout(imgSlide, dur);
    });
})();​

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