我要随时随机显示图片。但我需要一个不同的东西。
var images = []
images[0] = "img/y0.gif";
images[1] = "img/y1.gif";
images[2] = "img/y2.gif";
images[3] = "img/y3.gif";
images[4] = "img/y4.gif";
images[5] = "img/1.jpg";
images[6] = "img/2.jpg";
images[7] = "img/3.jpg";
usedImages = [];
setInterval(function () {changeImage();},100);
var changeImage = function () {
var index = Math.floor(Math.random() * (images.length)),
thisImage = images[index];
usedImages.push(thisImage);
images.splice(index, 1);
if (images.length < 1) {
images = usedImages.splice(0, usedImages.length);
}
var imgStr = '<img src="' + thisImage + '" alt = "">';
document.write(imgStr);
document.close();
}
我的代码有效但如果图像是gif间隔,则时间必须为500,或者如果图像是图像[2]则时间必须为500.
我该怎么做?
谢谢..
答案 0 :(得分:1)
您可以在setTimeout(function, delay)
内使用changeImage
,然后最初也会调用changeImage
。这将使您能够更改每个图像的延迟:
var images = []
images[0] = "img/y0.gif";
// ...
images[7] = "img/3.jpg";
usedImages = [];
changeImage();
function changeImage() {
var index = Math.floor(Math.random() * (images.length)),
thisImage = images[index];
// delay is 500 if image is .gif, and 100 if anything else
var delay = thisImage.match(/\.gif$/) ? 500 : 100;
setTimeout(changeImage, delay);
usedImages.push(thisImage);
images.splice(index, 1);
if (images.length < 1) {
images = usedImages.splice(0, usedImages.length);
}
var imgStr = '<img src="' + thisImage + '" alt = "">';
document.write(imgStr);
document.close();
}
答案 1 :(得分:0)
var changeImage = function () {
var index = Math.floor(Math.random() * (images.length)),
thisImage = images[index];
var msec = 0;
if(thisImage.split('.')[1] == 'gif'){
msec = 500;
}else{
msec = 300;
}
setTimeout(changeImage, msec)
usedImages.push(thisImage);
images.splice(index, 1);
if (images.length < 1) {
images = usedImages.splice(0, usedImages.length);
}
var imgStr = '<img src="' + thisImage + '" alt = "">';
document.write(imgStr);
document.close();
}