1

由于某种原因,clearTimeout函数在此脚本上不起作用


该脚本将

1) 自动播放整个 youtube 视频并使用 setTimeout 突出显示产品菜单中的活动步骤以继续下一步。这工作正常

2)单击菜单中的某个步骤时,自动播放应该停止。
-第 1 步:转到 youtube 视频的第 15 秒 - 播放到第 25 秒
-第 2 步:转到 youtube 视频的第 25 秒 - 播放到第 35 秒
当您在某个步骤上单击菜单时,setTimeout 函数仍然运行,所以在几秒钟后,调用 gotostep 函数,电影继续执行错误的步骤。

请问有人可以检查吗?

  <script type="text/javascript">
  $(document).ready(function(){
     gotostep('C9x4vG_6Qcs','1','1');});

 function gotostep(youtube,step,auto){
    var steparray=[15,25,35,48,58,65,79];
    var numbersteps=steparray.length-1;
    var i=1;
    var nextstep=parseInt(step)+1;
    while(i<=numbersteps){
       if(step==i){
         document.getElementById('step'+i+'').style.background='url("bg-button-active.jpg")';
         var timeout=steparray[step]*1000-steparray[step-1]*1000+3000;

         if(nextstep<=numbersteps && auto==1){
             var timer1=setTimeout('gotostep("'+youtube+'","'+nextstep+'","1")',timeout);
         }
         if(nextstep<=numbersteps && auto==0){
             clearTimeout(timer1);

         }

       }else{
         document.getElementById('step'+i+'').style.background='url("bg-button.jpg")';
       }

       i++;
     }
     var thestart=parseInt(steparray[step-1]);
     var theend=steparray[step];

     document.getElementById('productdemo-iframe').src="http://www.youtube.com/embed/"+youtube+"?autoplay=1&rel=0&start="+thestart+"&end="+theend+"";


}

代码

<div id="container">
<div id="left">
<iframe width="560" id="productdemo-iframe" height="315" src="http://www.youtube.com/embed/C9x4vG_6Qcs?rel=0&start=0" frameborder="0" allowfullscreen></iframe>

</div>
<div id="right">
<img src="logobw.jpg" alt="Logo" />
 <ul id="productdemo">
 <li><a id="step1" href="#" onclick="gotostep('C9x4vG_6Qcs','1','0');">1.&nbsp; Power button</a></li>
 <li><a id="step2" href="#" onclick="gotostep('C9x4vG_6Qcs','2','0');">2.&nbsp; Warming up</a></li>
 <li><a id="step3" href="#" onclick="gotostep('C9x4vG_6Qcs','3','0');">3.&nbsp; Insert cover</a></li>
 <li><a id="step4" href="#" onclick="gotostep('C9x4vG_6Qcs','4','0');">4.&nbsp; Cool down cover</a></li>
 <li><a id="step5" href="#" onclick="gotostep('C9x4vG_6Qcs','5','0');">5.&nbsp; Insert second cover</a></li>
 <li><a id="step6" href="#" onclick="gotostep('C9x4vG_6Qcs','6','0')">6.&nbsp; Turn off machine</a></li>
</ul>
</div>
</div>
4

1 回答 1

1

最简单的解决方法是替换var timer1=window.timer1=使 timer1 全局化。当您取消超时时,尚未设置 timer1,因为它已超出范围。在全局范围内添加另一个变量只是为了保存 timer1 值是不好的,但这是最快的解决方法。

关于代码的几件事:

  1. 请不要在您的 html 中使用 onclick,您使用的是 jQuery,因此您可以使用 $("slector").on("click",... 使用 li 的 id 来查看点击了什么。
  2. 将字符串传递给 setTimeout 是一个坏主意,它会使用 eval 来确定要做什么,看看下面的代码如何更好地做到这一点。
  3. 您使用变量 step 和 auto 作为字符串调用 gotoStep,但稍后您将它们与数字进行比较。这是有效的,因为您使用==而不是===. 最好传递数字并将数字与数字进行比较===

运行 setTimeout:

window.timer1=setTimeout(function(){
  gotostep(youtube,nextstep,1);
},timeout);
于 2013-06-25T08:43:49.523 回答