简体   繁体   中英

jQuery CSS Opacity Animate

So I'm trying to create a simple fading slideshow with five slides that repeats when finished.

I feel like what I've got should work, but it's not.

<script type="text/javascript">

    $(document).ready(function() {

        function playslide(){

            setTimeout(function(){
            $("#slide-two").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 10000);
            setTimeout(function(){
            $("#slide-three").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 20000);
            setTimeout(function(){
            $("#slide-four").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 1, 'swing')}, 30000);
            setTimeout(function(){
            $("#slide-five").animate({"opacity":"1"}, 2000, 'swing').delay(11000).animate({"opacity":"0"}, 2000, 'swing')}, 40000);

        }

        playslide();

        });
</script>

The idea is that the first slide will always have its opacity set to 1, so that when the last slide fades out, it's as if it's starting again. Each slide will hold for 10 seconds before fading out and after each slide fades in, the previous slide's opacity will be set back to 0 ready for the next time it repeats.

I hope it's not an obvious mistake. Apologies if it is...

Please why not use a .fadeIn() and .fadeOut() instead?

setTimeout(function () {
  $("#slide-two").fadeIn(400, function () {
    setTimeout(function () {
      $("#slide-two").fadeOut(function () {
      $("#slide-three").fadeIn(400, function () {
        // So on...
      });
    }, 1000);
  });
}, 1000);

Better to use these functions for doing it instead of you manually animating opacity.

https://jsfiddle.net/sk8ruo3u/

here's how I would do it

var list = ['.one','.two','.three','.four'];

$.each(list, function(index, value){
    changeOpacity(value, index*1000);    
});

function changeOpacity(target, timeout) {
    setTimeout(function () {
        $(target).animate({
            opacity: 0.05
        }, 1000);
    }, timeout);
};

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