我想在单击特定目标按钮时将属性autoplay
添加到<video></video>
元素。
<video controls>
<source src="video.mp4" type="video/mp4">
</video>
我尝试使用jQuery:
$('.targetButton').on('click', function(){
$('video').attr("autoplay"," ");
});
…但视频无法播放。我做错了什么?
设置自动播放标志不足以使视频播放,您应该在将自动播放设置为true后立即调用load()方法,以便视频将重新加载然后播放,因为标志为true。
$('video').autoplay = true;
$('video').load();
但是当你可以用JS播放视频时,为什么要这样做呢?下面是如何使用jQuery实现的:
$('video').play();
try this
var video = document.querySelector("#video"),
button = document.querySelector("button");
button.addEventListener("click", function() {
video.play()
//video.setAttribute("autoplay","autoplay")// this will set the attribute but will not play
}, false);
<p>
<button>playVideo</button>
</p>
<video id="video" controls="" preload="none" mediagroup="myVideoGroup" poster="https://media.w3.org/2010/05/sintel/poster.png">
<source id="mp4" src="https://media.w3.org/2010/05/sintel/trailer.mp4" type="video/mp4">
<source id="webm" src="https://media.w3.org/2010/05/sintel/trailer.webm" type="video/webm">
<source id="ogv" src="https://media.w3.org/2010/05/sintel/trailer.ogv" type="video/ogg">
<p>Your user agent does not support the HTML5 Video element.</p>
</video>
你可以用JavaScript来启用这个属性,但是你需要给video元素添加一个ID:
HTML<video id="myVideo" controls>
...
</video>
然后你可以获取元素并像这样设置属性:
JavaScriptdocument.getElementById("myVideo").autoplay = true;
为了更好地处理你的视频,最好使用html视频标签:
<div
class="modal fade"
id="exampleModal"
tabindex="-1"
aria-labelledby="exampleModalLabel"
aria-hidden="true"
>
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button
type="button"
class="btn-close"
data-bs-dismiss="modal"
aria-label="Close"
></button>
</div>
<div class="modal-body">
<div class="ratio ratio-16x9">
<video
id="myVideo"
controls
>
<source src="https://commondatastorage.googleapis.com/gtv-videos-bucket/sample/BigBuckBunny.mp4" type="video/mp4">
</video>
</div>
</div>
<div class="modal-footer">
<button
type="button"
class="btn btn-secondary"
data-bs-dismiss="modal"
>
Close
</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
你可以在javascript中使用play
和pause
事件:
const myModalOpen = document.getElementById("exampleModal");
exampleModal.addEventListener("shown.bs.modal", (event) => {
console.log("Abierto y autoplay");
const video = document.getElementById("myVideo");
video.play();
});
const myModalClose = document.getElementById("exampleModal");
exampleModal.addEventListener("hidden.bs.modal", (event) => {
console.log("Cerrado y stop");
const video = document.getElementById("myVideo");
video.pause();
});
使用视频控制:自动播放
<video controls autoplay>
<source src="video.mp4" type="video/mp4">
</video>
also you can include
- Play,暂停,寻求,体积,全屏切换,字幕/副标题(如有);Track(可用时)