Html HTML5 视频自动播放,但有 5 秒的延迟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20876864/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
HTML5 video autoplay but with a 5 seconds of delay
提问by Billy
I have a 20 second long HTML5 video loop as the background on my webpage and it is set to autostart. Is it possible to delay the video autoplay for 5 seconds? I am trying to allow the video to load completely before trying to play to prevent it from stuttering as much. Here is my current code:
我有一个 20 秒长的 HTML5 视频循环作为我网页上的背景,它被设置为自动启动。是否可以将视频自动播放延迟 5 秒?我试图让视频在尝试播放之前完全加载,以防止它尽可能地卡顿。这是我当前的代码:
<video id="video_background" poster="images/dmm_background.jpg" controls="controls" preload="true" autoplay="true" loop="loop" muted="muted" volume="0">
<source src="videos/backgroundvideo.mp4" type="video/mp4">
<source src="videos/backgroundvideo.webm" type="video/webm">
</video>
</video>
Any help is greatly appreciated!!
任何帮助是极大的赞赏!!
回答by Drew Beres
HTML:
HTML:
<video id="myVideo" src="http://www.quirksmode.org/html5/videos/big_buck_bunny.mp4">
JavaScript:
JavaScript:
setTimeout(function(){
document.getElementById("myVideo").play();
}, 5000);
回答by Joe Johnston
This is a working solution for me. You should use canplayas a best practice to be sure the browser can playthe video. Also, here is a straight javascript solution.
这对我来说是一个有效的解决方案。您应该使用canplay作为最佳实践,以确保浏览器可以播放视频。此外,这是一个直接的 javascript 解决方案。
Note: I removed autoplay, an extra closing video tag, and formatted your muted & loop flags.
注意:我删除了自动播放、一个额外的结束视频标签,并格式化了您的静音和循环标志。
var video = document.getElementById("video_background");
video.addEventListener("canplay", function() {
setTimeout(function() {
video.play();
}, 5000);
});
<video id="video_background" poster="images/dmm_background.jpg" controls="controls" preload="true" muted loop>
<source src="https://d2v9y0dukr6mq2.cloudfront.net/video/preview/SsRadVyPGjdkeg9tt/videoblocks-computer-hacking-in-process-cyber-security-concept_h-l3zbu4xb__PM.mp4">
<source src="videos/backgroundvideo.webm" type="video/webm">
</video>