开发者

Dynamically changing images in a div

开发者 https://www.devze.com 2023-01-11 01:37 出处:网络
I\'ve fi开发者_C百科ve images and would like to display it in a same div one by one with interval of 2 sec. Can anyone please suggest any solution for this?Simple javascript example:

I've fi开发者_C百科ve images and would like to display it in a same div one by one with interval of 2 sec. Can anyone please suggest any solution for this?


Simple javascript example:

var currentImage = 0;
var images = [
    'a.jpg',
    'b.jpg'
];
var imageElement = document.getElementById('yourImageTagId');

function nextImage(){
    currentImage = (currentImage + 1) % images.length;
    imageElement.src = images[currentImage];
}

var timeoutId = setTimeout(nextImage, 1000);

It expects you to have some html like this:

<img src="a.jpg" id="yourImageTagId" />


Jquery Cycle is really flexible... you could hook it up to whatever youve got already marked up pretty easily.


There are many ways to do this nowadays but one simple way is using the following jquery plugin:

http://jquery.malsup.com/cycle/

Here is a simple demo in action fading images one after the other.

http://jquery.malsup.com/cycle/basic.html


setTimeout

You can do something like this.

function selectData(currentIndex) {
    // select current's element "display" to "none" and show next element
    ...

    // schedule next change in two second        
    setTimeout("selectData(" + nextIndex + ");", 2000);
};

I assume all images are inside that div already and have style display:none

0

精彩评论

暂无评论...
验证码 换一张
取 消