2011-07-05 156 views
0

我正在使用以下脚本和以后的onclick事件。如果我使用onclick,我的旋转横幅会丢失,并开始以随机间隔显示图片。我想我应该在第一段代码的末尾重写“setTimeout”。问题是如何?如何将事件添加到自动旋转图像?

<script language="JavaScript" type="text/javascript"> 
<!-- 
var RotatingImage1_Index = -1; 
var RotatingImage1_Images = new Array(); 
RotatingImage1_Images[0] = ["images/ban_image1.png","",""]; 
<!-- 15 Images in total--> 
RotatingImage1_Images[14] = ["images/ban_image2.png","",""]; 

function RotatingImage1ShowNext(){ 
RotatingImage1_Index = RotatingImage1_Index + 1; 
    if (RotatingImage1_Index > 14) 
    RotatingImage1_Index = 0; 
    eval("document.RotatingImage1.src = RotatingImage1_Images[" + RotatingImage1_Index + "][0]"); 
    setTimeout("RotatingImage1ShowNext();", 4000);} 
// --> 
</script> 
<img src="images/ban_image1.png" id="ban_img1" name="RotatingImage1"> 

这部分工作,因为它应该。

<div id="ban_next" align="left"> 
<a href="#" onclick="RotatingImage1ShowNext();return false;"> 
<img src="images/ban_next.png" id="ban_nxt1"></a></div> 

这部分也适用,但只有在将'setTimeout'设置为'0'时才正确。我很抱歉,我完全是这个新手。我在看this stackoverflow.com question,但我不知道如何在这里实现。

我提前感谢你。

编辑: 旋转图像自动启动。它每4秒显示一个新图像。图像上有文字,或更好的内幕笑话。读者应该尝试阅读它们,但是如果自动旋转在那里发生,必须保持整整一分钟才能看到所有图像。这可能会很长。所以我想实现一个按钮来覆盖计时器并显示下一个图像'点击'。但点击后,旋转时间应该变回自动旋转。这是计划。

谢谢Prusse,现在它睡觉时,我会尽量把握你的答案明天;)

+0

你想要onclick事件做什么?文档加载时横幅是否旋转,并且点击应使其停止? – tkm256

回答

0

你不需要的eval,只是做document.RotatingImage1.src = RotatingImage1_Images[RotatingImage1_Index][0]

所描述的行为发生是因为有多个定时器触发。第一次有一套RotatingImage1ShowNext被调用,每次从你的onclick处理函数调用它时会多一个。要解决此问题,请为您的计时器声明一个全局值,并在设置另一个超时值之前将其清除。像:

var global_timerid; 
function RotatingImage1ShowNext(){ 
    //RotatingImage1_Index = RotatingImage1_Index + 1; 
    //if (RotatingImage1_Index > 14) RotatingImage1_Index = 0; 
    RotatingImage1_Index = (RotatingImage1_Index + 1) % RotatingImage1_Images.length; 
    //document.RotatingImage1.src = RotatingImage1_Images[RotatingImage1_Index][0]; 
    document.getElementById('ban_img1').src = RotatingImage1_Images[RotatingImage1_Index][0]; 
    if (global_timerid) clearTimeout(global_timerid); 
    global_timerid = setTimeout(RotatingImage1ShowNext, 4000); 
} 
+0

谢谢Prusse,我必须承认,我没有使用你的答案。也许别人可以使用它。对于那些寻找这样的人,我现在使用[jQuery.mb.scrollable](http://pupunzi.com/#mb.components/mb.scrollable/scrollable.html)。 – Kamps