Auto-play an HTML5 video on Dom Load using jQuery

落爺英雄遲暮 提交于 2019-12-19 17:42:22

问题


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

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)

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

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


回答1:


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

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

before using .play() method:

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

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

<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>



回答2:


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

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



回答3:


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

As Justin McDonald noted, the play() method exists on the Video DOM Node itself, 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 video Node.



来源:https://stackoverflow.com/questions/15842308/auto-play-an-html5-video-on-dom-load-using-jquery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!