我在网站上有一个使用 <video>
的视频标签。
我想平稳地更改视频源,而视频不会在短时间内出现故障。
这就是我的意思:http://i.imgur.com/VD4FTpp.gif
如您所见,视频在加载新源期间丢失了宽度/高度,我用红色边框来显示效果。
可以重现问题的代码:
<html>
<head>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
</head>
<video preload="metadata" autoplay poster="data:image/gif,AAAA" class="preview-video" id="video" style="border: 5px red solid;">
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" id="videoSource">
Your browser does not support the video tag.
</video>
<br />
<br />
<button id="loadOther">Next Video</button>
<script>
$("#loadOther").click(function() {
$("#videoSource").attr("src", "http://www.w3schools.com/html/mov_bbb.mp4");
$("#video")[0].load();
});
</script>
</html>
最佳答案
如果您真正想要的是避免宽度/高度在下一个视频加载时返回默认值 (300 x 150),您只需设置 <video>
的 width
和 height
加载视频的属性(videoWidth
和 videoHeight
是媒体的实际值,而不是元素的值)。
// fix the element's width and height properties to the current video ones
$("#video").on('loadedmetadata', function() {
this.width = this.videoWidth;
this.height = this.videoHeight;
});
$("#loadOther").click(function() {
$("#videoSource").attr("src", "http://www.w3schools.com/html/mov_bbb.mp4");
$("#video")[0].load();
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<video preload="metadata" autoplay poster="data:image/gif,AAAA" class="preview-video" id="video" style="border: 5px red solid;">
<source src="http://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4" id="videoSource">
Your browser does not support the video tag.
</video>
<br />
<br />
<button id="loadOther">Next Video</button>
但是,如果下一个加载的媒体与前一个媒体的尺寸不同,此代码也会更改元素的宽度和高度。为避免它,只需使用 .one()
或在事件监听器触发后将其移除。
关于jquery - 加载其他源时 HTML5 视频大小发生变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41213501/