我想在javascript中循环一系列图像。下面是我到目前为止的代码
<html>
<head>
</head>
<body>
<img src="images/image1.jpg" alt="rotating image" width="600" height="500" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'); // change to match image ID
//var imageDir = 'images/'; // change to match images folder
var delayInSeconds = 1; // set number of seconds delay
// list image names
var images = ['1.jpg','2.jpg', '3.jpg', '4.jpg'];
// don't change below this line
var num = 0;
var changeImage = function() {
var len = images.length;
rotator.src = images[num++];
if (num == len) {
num = 0;
}
};
setInterval(changeImage, delayInSeconds * 50);
})();
</script>
</body>
</html>
它只能显示我在“var image”中声明的图像。如果我有10000张图片,怎么做。我试过使用'for'循环,但它失败了..任何建议?提前谢谢
=============================================== ===============
更新Joseph推荐的版本:
<html>
<head>
</head>
<body>
<img src="images/1.jpg" alt="rotating image" width="600" height="500" id="rotator">
<script type="text/javascript">
(function() {
var rotator = document.getElementById('rotator'), //get the element
var delayInSeconds = 1, //delay in seconds
var num = 0, //start number
var len = 9999; //limit
setInterval(function(){ //interval changer
num = (num === len) ? 0 : num; //reset if limit reached
rotator.src = num + '.jpg'; //change picture
num++; //increment counter
}, delayInSeconds * 1000);
}());
</script>
</body>
</html>
答案 0 :(得分:2)
假设图像具有相同的顺序文件名,这在循环其中很多时最好:
(function() {
var rotator = document.getElementById('rotator'), //get the element
dir = 'images/', //images folder
delayInSeconds = 1, //delay in seconds
num = 0, //start number
len = N; //limit
setInterval(function(){ //interval changer
rotator.src = dir + num+'.jpg'; //change picture
num = (num === len) ? 0 : ++num; //reset if last image reached
}, delayInSeconds * 50);
}());
答案 1 :(得分:0)
AFAIK,您可以使用相同的逻辑以小块显示图像,因为如果您尝试同时显示所有10000个图像,浏览器将会崩溃。因此,使用您当前的逻辑和页面在页面上显示5-10个图像。要求用户检索下一组。您可以在许多图像共享应用程序中看到这种实现。希望这会对您有所帮助