这是一个循环播放整个窗口和自动播放的视频示例。它是通过 JavaScript 按需创建的。
我需要这个视频只应在请求时加载和播放,即不是在页面的每次加载时。(用 隐藏元素是display: none;
不行的,因为即使没有显示,视频仍然会加载。)
JavaScript
/**
* Create the video.
*
* An alternative might have been to use an HTML template tag inside the Twig template,
* to then create an element and append it. But this worked only in Chrome:
* - in Firefox, `autoplay loop muted` (inside the <template>) get converted to
* `autoplay="" loop="" muted=""` (in the Inspector) and there's no playback.
* - in Safari, nothing happens.
*
* Another alternative (that worked this one) is to just append the whole HTML as a
* single string, but it's harder to read.
*/
var video = $('<video />', {
id: 'video',
class: 'myclass',
poster: 'https://path/to/my/poster.jpg'
}).prop({
muted: true,
autoplay: true,
loop: true,
});
var src1 = $('<source />', {
type: 'video/webm', // for Firefox, Chrome; slightly smaller file size
src: 'https://path/to/my/video.webm'
}).appendTo(video);
var src2 = $('<source />', {
type: 'video/mp4', // for Safari, Firefox, Chrome
src: 'https://path/to/my/video.mp4'
}).appendTo(video);
video.appendTo($('body'));
注意:
muted
, autoplay
,loop
必须进去prop()
。将它们设置为属性将不起作用!(并且会产生很大的误导,因为你会认为你设置了它们,而实际上你并没有。)
muted
Chrome 中需要它autoplay
才能工作。
- 创建海报的一种简单方法:用 VLC 打开视频,拍一张
Snapshot
,将生成的 PNG 转换为 JPG。
- 确保视频已正确转换。并非所有 MP4 文件都可以在浏览器中使用。这被证明是有用的:使用 FFmpeg (for Web) 进行视频转换。
上面提到的难以阅读的替代方案:
$('body').append('<video class="c-congrats c-congrats--outofnew" autoplay loop muted> <source src="https://path/to/my/video.webm" type="video/webm" /> <source src="https://path/to/my/video.mp4" type="video/mp4" /> Your browser does not support the video tag. </video>')
CSS
.myclass {
position: fixed;
z-index: -1;
height: 100vh;
top: 0;
left: 0;
}