如何将事件添加到自动旋转图像?

时间:2011-07-05 16:50:13

标签: javascript override banner

我正在使用以下脚本和后来的onclick-event。如果我使用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,现在睡觉了,明天我会尽力把握你的答案;)

1 个答案:

答案 0 :(得分: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);
}