2010-10-31 184 views
1

我在頁面上有圖像標記。我需要該標籤每1秒顯示不同的圖像。我的照片存儲在「pict」文件夾中。如何使用JQuery實現這一點?使用JQuery更改圖像

回答

2

我使用的一個簡單的圖像旋轉器如下。您需要使用某種服務器端語言將所有圖像渲染成您的文件夾中的div

看到它在這裏工作:http://jsbin.com/iledo3

如果你有大量的圖片,我建議先預加載它們。

HTML:

<div id="slideshow-container"> 
    <div id="slideshow"> 
     <img src="img/home-1.jpg"> 
     <img src="img/home-2.jpg"> 
     <img src="img/home-3.jpg"> 
    </div> 
</div> 

CSS:

#slideshow-container { height:410px; position:relative; } 
#slideshow-container img { position:absolute; left:0; top:0; width:100%; height:100% } 
#slideshow  { position:absolute; left:0; top:0; width:100%; height:100%; list-style:none } 
#slideshow img { width:904px; height:410px; background-repeat:none; background-position:top left; position:absolute; left:0; top:0 } 
#slideshow  { position:absolute; left:0; top:0; width:100%; height:100%; } 
#slideshow img { width:904px; height:410px; background-repeat:none; background-position:top left; position:absolute; left:0; top:0 } /* adjust this for your images */ 

的jQuery:

$('#slideshow img:gt(0)').hide(); //hide all images except first initially 
    setInterval(function(){ 
     $('#slideshow :first-child').fadeOut('slow') 
     .next('img').fadeIn('slow') 
     .end().appendTo('#slideshow');}, 
     2000); //2 second interval 
+0

非常感謝莫因! – Damir 2010-10-31 15:33:32

+0

但是當我登錄頁面時發生了一些奇怪的事情。我把6張圖片,當加載頁面畫廊閃爍快一輪PIC - 1 PIC - 6 PIC - 2 PIC - 6 PIC - 3 PIC - 6 PIC - 4 PIC - 6 PIC - 5 PIC - 6,之後,它很好!這是隱藏問題嗎? – Damir 2010-10-31 16:14:16

+0

我已經通過一個小小的更改更新了我的答案。你現在可以試試嗎? – 2010-10-31 20:54:35

1

您可以獲取img元素並使用attr method來更改它的src,或者使用不同的img元素來更改它。無論哪種方式,您可能都想使用setInterval來處理時間。

2

將所有圖像源存儲在一個數組中,然後如果要隨機選擇一個,請使用Math.random函數,最後使用jQuery.attr()來切換圖像的src屬性。所有這些都應該在每秒觸發的函數中。下面的代碼的草稿版本,假設你的圖像存儲在images文件夾相對於您目前的網址:

function imageRotate() { 
    var images = ["image1.jpg", "image2.jpg", "image3.jpg", "image4.jpg"]; 
    var i = Math.floor(Math.random() * images.length); 
    jQuery('#my-image').attr("src", "/images/" + images[i]); 
    setTimeout('imageRotate()', 1000); // Re-launch after one second 
} 
setTimeout('imageRotate()', 1000); // First launch after 1 second interval 

或者你可以嘗試jQuery Cycle plugin

4

例子:http://jsfiddle.net/8GkS7/

$(function() { 
    var images_array = [ 
     "/pict/image0.jpg", 
     "/pict/image1.jpg", 
     "/pict/image2.jpg", 
     "/pict/image3.jpg", 
     "/pict/image4.jpg" 
    ]; 

    var i = 0; 
    var len = images_array.length; 
    var $img = $('#myImage'); 

    setInterval(function() { 
     $img.attr('src', images_array[ i++ % len]); 
    }, 1000); 
}); 

或者,如果你的圖片進行編號一樣的是,你實際上可以不用數組做到這一點:

$(function() { 
    var i = 0; 
    var len = 5; // Total number of images 
    var $img = $('#myImage'); 

    setInterval(function() { 
     $img.attr('src', "/pict/image" + (i++ % len) + ".jpg"); 
    }, 1000); 
}); 

編輯:注意使用第二個示例中,圖像的索引號必須以0開頭。如果他們以1開頭,則需要(i++ % len + 1)