How can I rotate(or change) background image using CSS and Javascript

后端 未结 3 840
执笔经年
执笔经年 2021-01-06 19:25

I have taken a look through stackoverflow for hours now, and I have found a topic similar to what I am trying to achieve

JavaScript, How to change the background of

3条回答
  •  耶瑟儿~
    2021-01-06 20:21

    You could try using different classes for each image, and then just swap out CSS classes in a given interval.

    $(document).ready(function(){
      var seconds = 5000;
      var step = 0;
      var limit = 5;
    
      $("#Background").addClass("image-"+step);
    
      setInterval(function(){
        $("#Background").removeClass("image-"+step);
        step = (step > limit) ? 0 : step + 1;
        $("#Background").addClass("image-"+step);
      },seconds);
    });
    

    I'm not sure what kind of animation you are trying to do, but you could fadeOut and then fadeIn.

    $(document).ready(function(){
      var seconds = 5000;
      var step = 0;
      var limit = 5;
    
      $("#Background").addClass("image-"+step).fadeIn(500);
    
      setInterval(function(){
        $("#Background").fadeOut(500,function(){
           $(this).removeClass("image-"+step);
           step = (step > limit) ? 0 : step + 1;
          $("#Background").addClass("image-"+step).fadeIn(500);
        });
      },seconds);
    });
    

提交回复
热议问题