我正在尝试开发幻灯片,幻灯片之间有暂停.所以我正在尝试使用setTimeout语句,如下所示.这是写入交换2.jpg为1.jpg,点击按钮暂停10秒.但现在确实有效.谁能帮我.谢谢.
<html>
<head>
<script type="text/javascript">
var t;
function swap(newImage) {
var fileName=newImage.toString()+".jpg"
document.slideshow.src=fileName
t=setTimeout("swap()",10000)
}
</script>
</head>
<body>
<img name="slideshow" src="1.jpg" width="450" height="335" />
<br /><br />
<input type="button" onClick="swap('2')" value="Change image" />
<br /><br />
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
这里有一些问题.首先,不推荐在setTimeout的第一个参数中进行eval的传递代码.更好地传递一个回调:
setTimeout(function() { swap(); },10000);
//Or
setTimeout(swap,10000); //Passing the actual function as the callback
Run Code Online (Sandbox Code Playgroud)
其次,您在超时内调用没有参数的swap()方法.它应传入一个新的图像文件名(可能通过声明一个文件名数组),或检查参数是否设置.
function swap(newImage,element) {
if(newImage) {
var fileName = newImage.toString()+".jpg";
element.src = fileName;
}
t=setTimeout(this,10000)
}
Run Code Online (Sandbox Code Playgroud)
第一次运行后,此功能显然不会执行任何操作(因为没有提供新的图像文件名).使用数组,您可以迭代几个文件名:
var images = ['1.jpg','2.jpg','3.jpg'];
var slideshow = function(element, images, index) {
if(!index || ( (index + 1) > images.length) ) index = 0;
element.src = images[index];
t = setTimeout(function(){
slideshow(element, images, index + 1);
},10000)
};
//Fetch the image element the slideshow is running on
var element = document.slideshow;
slideshow(element, images);
Run Code Online (Sandbox Code Playgroud)
这将继续在阵列中的图像之间切换,直到超时被取消.
| 归档时间: |
|
| 查看次数: |
5026 次 |
| 最近记录: |