Cam*_*ron 1 html javascript google-chrome
我有一个视频(用于背景目的),该视频已静音,我打算自动播放。如果我将以下代码放入 html 文件中:
<video playsinline autoplay muted loop>
<source src="https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4">
</video>
Run Code Online (Sandbox Code Playgroud)
它在 Chrome 上运行得很好。
然而,如果我使用 DOM 操作插入完全相同的视频,我会在 Chrome 上遇到麻烦,但在 Firefox 等其他浏览器中会成功。
<html>
<body>
</body>
<script>
function render() {
const video = document.createElement('video');
video.setAttribute('muted', true);
video.setAttribute('autoplay', true);
video.setAttribute('loop', true);
video.setAttribute('playsinline', true);
const source = document.createElement('source');
source.setAttribute('src', 'https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4');
video.appendChild(source);
document.body.appendChild(video);
}
render();
</script>
</html>
Run Code Online (Sandbox Code Playgroud)
Chrome 因阻止自动播放而臭名昭著。一般的解决方案是要么静音(我已经这样做了),要么使用 dom 操作来调用 play(这不起作用)。将视频插入 dom 后,有没有办法让它发挥作用。我关心的原因是因为我的实际网站需要渲染所有内容(我的网站位于 ember.js 中)。
这是 Chrome 版本 71 中的内容。
谢谢!
这可能是一个错误(而且不是唯一具有此自动播放政策的错误......)。
当您muted通过 设置属性时Element.setAttribute(),策略不会像应有的那样释放。
要解决此问题,请通过 Element 的属性设置 IDL 属性:
function render() {
const video = document.createElement('video');
video.muted = true;
video.autoplay = true;
video.loop = true;
video.setAttribute('playsinline', true);
const source = document.createElement('source');
source.setAttribute('src', 'https://res.cloudinary.com/dthskrjhy/video/upload/v1545324364/ASR/Typenex_Dandelion_Break_-_Fade_To_Black.mp4');
video.appendChild(source);
document.body.appendChild(video);
}
render();
Run Code Online (Sandbox Code Playgroud)
作为一个小提琴,因为 StackSnippets 需要来自父页面的单击事件,无论如何总是允许自动播放;-)。
| 归档时间: |
|
| 查看次数: |
1751 次 |
| 最近记录: |