如何禁用HTML5视频自动播放?
我尝试过的方法:
<video width="640" height="480" controls="controls" type="video/mp4" autoplay="false" preload="none"><source src="http://mydomain.com/mytestfile.mp4">Your browser does not support the video tag.</video>
如何禁用HTML5视频自动播放?
我尝试过的方法:
<video width="640" height="480" controls="controls" type="video/mp4" autoplay="false" preload="none"><source src="http://mydomain.com/mytestfile.mp4">Your browser does not support the video tag.</video>
我会移除 autoplay
属性,因为如果浏览器遇到它,它会自动播放!
autoplay
是一个HTML布尔属性,但需要注意的是,值true
和false
是不允许的。要表示false值,必须省略该属性。
布尔属性上不允许使用“true”和“false”值。要表示false值,必须完全省略该属性。
此外,类型应该放在source标签内,如下所示:
<video width="640" height="480" controls preload="none">
<source src="http://example.com/mytestfile.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
参考资料:
autoPlay
属性不是布尔类型的一种,但它确实明确说明了:“autoplay属性是一个布尔属性。当存在时,用户代理(如本文所述的算法)将在可以在不停止播放媒体资源的情况下立即开始播放。” W3C学校也同样指出:https://www.w3schools.com/tags/att_video_autoplay.asp - myermian移除视频标签中的自动播放。可以使用以下代码:
<video class="embed-responsive-item" controls>
<source src="http://example.com/video.mp4">
Your browser does not support the video tag.
</video>
它是百分百有效的。
尝试在你的源代码标签中添加 autostart="false"
。
<video width="640" height="480" controls="controls" type="video/mp4" preload="none">
<source src="http://example.com/mytestfile.mp4" autostart="false">
Your browser does not support the video tag.
</video>
实际上,将autoplay
设置为false
并不能完全解决问题,有些视频仍然会自动播放。请参见此案例在fiddle中的表现。
如果您想要暂停所有视频,可以通过以下代码来实现:
videos = document.querySelectorAll("video");
for(video of videos) {
video.pause();
}
video
标签在一个影子根元素中,上述情况将无法实现,但是几乎任何通用解决方案都不适用于影子根元素。 在这种情况下,您需要采用自定义方法并首先扩展影子根。只需在您的视频标签中使用preload="none"
,当页面加载时,视频将停止自动播放。
移除所有属性,这些属性说其存在于您的标记中是一个布尔简写为true的autoplay
。
此外,请确保始终使用video
或audio
元素。不要使用object
或embed
,因为这些元素默认使用第三方插件自动播放,并且无法在没有更改浏览器设置的情况下停止。
我想在编辑模式下将autoplay设置为“false”,但在查看器模式下将其设置为“true”,并通过仅在查看器模式下使用jQuery添加属性来解决了这个问题:
<video id="vid" class="my-vid" poster="https://poster-url/poster.jpg"
loop="loop" controls="controls" width="100%" height="100%">
<source src="https://video-url/vision.mp4" type= "video/mp4" />
</video>
<script type="text/javascript">
if (document.location.href.indexOf('domain') > -1 ||
document.location.href.indexOf('test') > -1) {
$(document).ready(function() {
$('video').attr('autoplay','autoplay')
});
}
</script>
<video class="embed-responsive-item" controls>
<source src="http://example.com/video.mp4" autostart="false">
Your browser does not support the video tag.
</video>
您可以设置 autoplay=""
<video width="640" height="480" controls="controls" type="video/mp4" autoplay="">
<source src="http://example.com/mytestfile.mp4">
Your browser does not support the video tag.
</video>
提示:可以使用autoplay
或autoplay="autoplay"
来启用。