jquery - 加载其他源时 HTML5 视频大小发生变化

标签 jquery css html html5-video

我在网站上有一个使用 <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>widthheight加载视频的属性(videoWidthvideoHeight 是媒体的实际值,而不是元素的值)。

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

相关文章:

css - 纯使用css影响 'cousin'元素

带有 optgroups 的 html 表单不会改变大小

javascript - 无法从 JavaScript 中的 Flask 模板变量访问列表元素

twitter-bootstrap - 为什么 Bootstrap 将 line-height 属性设置为 1.428571429?

javascript - 为什么我网站上的头像链接会泄露?

javascript - 附加带有选择选项字段的表单

jquery - 使用 jquery 识别是否有子菜单

html - ul/li 导航中彼此相邻的两个 anchor 标记

html - 当图像实际上是图片标签时,如何定义图像的微数据标记?

Javascript 防止在浏览器窗口外拖放