2014-10-09 128 views
0

我的圖片文件夾中有5張jpg圖片。我想要一個div自動改變背景。如何使用jQuery做到這一點?如何使用jQuery不斷更改div的背景圖像?

我可以使用jQuery一次操作背景屬性,但當我嘗試自動更改並循環時,我卡住了。

$(document).ready(function() { 
    $(".topstrip").css('background-image', 'url("/static/img/website/banner/factory_plane-normal.jpg")') 
}); 
+0

的,什麼是你試試?顯示我們的代碼。 – vaso123 2014-10-09 11:19:11

回答

5

使用setInterval函數。示例代碼。

   $(document).ready(function() { 
       var imageFile = ["Image.jpg", "Image1.jpg", "Image2.jpg", "Image4.jpg"]; 
       var currentIndex = 0; 
       setInterval(function() { 
        if (currentIndex == imageFile.length) { 
         currentIndex = 0; 
        } 
        $(".topstrip").css('background-image', 'url("/static/img/website/banner/' + imageFile[currentIndex++] + '")'); 
       }, 3000); 
      }); 
+0

看起來很乾淨。但僅顯示第一張圖像。索引錯過了? – 2014-10-09 11:55:35

+0

現在只需檢查代碼 – 2014-10-09 11:58:50

+0

工程就像魅力!感謝Aravind。 – 2014-10-09 12:00:17

0
<div class="topstrip" style="height:100px;width:100px;"></div> 

    <script> 
    var imagebackground = 0; 
    var imgbackgrounds = []; 
    imgbackgrounds[0] ='/images/image1.jpg'; 
    imgbackgrounds[1] ='/images/image2.jpg'; 
    imgbackgrounds[2] ='/images/image3.jpg'; 
    imgbackgrounds[3] ='/images/image4.jpg'; 
    imgbackgrounds[4] ='/images/image5.jpg'; 


    function changeimage() { 
     imagebackground++; 
     if(imagebackground > 4) imagebackground = 0; 

     $('.topstrip').fadeToggle("slow",function() { 
      $('.topstrip').css({ 
       'background-image' : "url('" + imgbackgrounds[imagebackground] + "')" 
      }); 
      $('.topstrip').fadeToggle("slow"); 
     }); 


     setTimeout(changeimage, 5000); 
    } 

    $(document).ready(function() { 
     setTimeout(changeimage, 5000);   
    }); 
    </script>