2017-10-15 136 views
0


我试图在视频开始播放5秒后向视频添加一个'onclick'事件监听器,它应该将用户重定向到某个URL。我当前的js代码:在播放视频后执行任务几秒钟

document.getElementById('my_video_1').addEventListener("timeupdate", myfunc, false); 

    function myfunc() { 
     console.log('in my func'); 
     if (this.currentTime > 5) { 
      console.log('in if'); 
      this.onclick = function() { 
       location.href = "www.google.com"; 
      }; 
     } 
    } 

问题是,它似乎每次'timeupdate'触发时都会执行该函数。但是,一旦视频当前时间达到5,然后完成执行myfunc,我想将onclick处理程序分配给视频。
任何想法,我可以做到这一点? 有没有更好的方法来达到我的目的?

+0

一,二circunstances了'timeupdate'触发事件是在播放视频时([W3Schools的]的(HTTPS ://www.w3schools.com/tags/av_event_timeupdate.asp))。如果您不希望每次事件触发时执行您的函数,我建议首先将'click'事件添加到视频元素,然后使用'currentTime'属性。 – CrisMVP3200

+0

@ CrisMVP3200你能给我一个示例代码吗? –

+0

@MissCode当然,下面检查;) – CrisMVP3200

回答

1

正如我在评论中提到的,而不是使用timeupdate事件(这意味着你的函数,每次执行您的视频播放时间,或它的播放位置移动),最好是只使用click事件,(与addEventListener方法或与onclick属性)。

/* Attach the click event with the addEventListener() method 
    By default, the third parameter, useCapture, is false */ 
document.getElementById("my_video_1").addEventListener("click", myfunc); 

/* Attach the click event with the onclick property */ 
document.getElementById("my_video_1").onclick = myfunc; 

然后,通过谁click事件trigerring执行该功能,你检查视频的当前时间超过5秒。

function myfunc() { 
    if (this.currentTime > 5) { 
     location.href = "http://www.google.com"; 
    }; 
} 

这是完整的示例代码(包含HTML和JavaScript):

<!DOCTYPE html> 
<html lang="es"> 
    <head> 
     <meta charset="UTF-8"/> 
    </head> 
    <body> 
     <video id="my_video_1" width="426px" height="240px" autoplay controls muted> 
      <source src="https://media.w3.org/2010/05/sintel/trailer.mp4" type="video/mp4"/> 
     </video>  
    </body> 
    <script> 
     document.getElementById("my_video_1").addEventListener("click", myfunc); 
     // document.getElementById("my_video_1").onclick = myfunc; 

     function myfunc() { 
      if (this.currentTime > 5) { 
       location.href = "https://www.google.com"; 
      }; 
     } 
    </script> 
</html> 
+0

是的。这工作正常。 TNX –

相关问题