Html 使用 jQuery 在 Dom Load 上自动播放 HTML5 视频

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15842308/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:15:33  来源:igfitidea点击:

Auto-play an HTML5 video on Dom Load using jQuery

htmlhtml5-video

提问by Jamie Fearon

I'm trying to play a video as soon as the dom has loaded using jQuery. This is my code:

我正在尝试使用 jQuery 加载 dom 后立即播放视频。这是我的代码:

HTML

HTML

<video id="video" width="420">
  <source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
  <source src="http://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">
  <p>Your browser does not support HTML5 video.</p>
</video>

JS (script.js)

JS(脚本.js)

$(document).ready(function() {
  $(#video).play();
});

When you dom loads the video does not play, where am I going wrong? Thanks in advance.

当你dom加载视频不播放,我哪里错了?提前致谢。

回答by Justin McDonald

The jQuery selector $("#video")returns a jQuery object. Since play()is a function of the DOM element, you must get the DOM element with:

jQuery 选择器$("#video")返回一个 jQuery 对象。由于play()是 DOM 元素的函数,您必须通过以下方式获取 DOM 元素:

$("#video").get(0);

before using .play() method:

在使用 .play() 方法之前:

$("#video").get(0).play();

Edit: You can also use HTML5 selected tags in case jQuery fall back. Note the autoplaytag.

编辑:您还可以使用 HTML5 selected 标签以防 jQuery 回退。注意autoplay标签。

<video controls="controls" autoplay="autoplay" loop="loop"
width="233" height="147" poster="//www.cdn.com//video.png"
preload="auto" title="Video">
    <source src="//www.cdn.com/video.mp4" type="video/mp4"/>
    <source src="//www.cdn.com/video.ogv" type="video/ogv"/>
    <source src="//www.cdn.com/video.webm" type="video/webm"/>
</video>

回答by insecureabnormality

I know is not jQuery but in standard javascript with html5 you can use:

我知道不是 jQuery,而是在带有 html5 的标准 javascript 中,您可以使用:

var video = document.getElementById("target_video");
video.autoplay = true;
video.load(); 

回答by mattavatar

$('video#video').each( (i,e) => e.play() );

As Justin McDonaldnoted, the play()method exists on the Video DOM Nodeitself, so you first have to resolve the jQuery Object to the specific Node. However, his solution will throw an error if the element with id="video"does not exist or is not a videoNode.

正如Justin McDonald 所指出的,该play()方法存在于Video DOM 节点本身,因此您首先必须将 jQuery 对象解析为特定节点。但是,如果元素id="video"不存在或不是video节点,他的解决方案将抛出错误。