2010-10-31 97 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)