当通过JavaScript插入HTML时,静音视频无法自动播放
我正在尝试通过JavaScript插入HTML5 <
元素,但是尽管它是 muted ,但它仍未自动播放。
背景上下文
我想将所有GIF资产转移到MP4格式。同样,我想让HTML 视频
模仿GIF。它应该包括以下属性:
- 网页
- 加载
- 循环无限期地
- 播放
我目前在Chrome 100中
。
一旦 t123278/pen/exoqxyb?editors = 1111“ rel =“ nofollow noreferrer”>此codepen 。我想通过JavaScript动态添加HTML视频。但是,即使指定了自动播放和静态属性,这也无法自动播放。
但是,如果我的视频元素具有直接在HTML中写入相同属性的视频元素,则自动播放功能效果很好。
如何使用JS 和将视频插入自动播放?
I am trying to insert a HTML5 <video>
element through Javascript, but it fails to autoplay despite it being muted.
Background Context
I would like to transfer all of my gif assets over to mp4 format. Likewise, I would like to have the HTML video
emulate a gif. It should include the following properties:
- Be muted
- Autoplays as soon as the webpage loads
- Loop indefinitely
- Plays in line
I am currently on Chrome 100.
What I've Tried
Relevant code is held within this codepen. I want to add the HTML video dynamically through javascript. But this fails to autoplay even though both autoplay and muted attributes are specified.
However, if I have the video element with the same attributes directly written within the HTML, the autoplay functionality works just fine.
How do I insert the video with JS and get it to autoplay?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我认为您宁愿设置这样的属性:
尝试进行这些修改。如果它仍然不起作用,则可以在上述代码之后添加此内联:
I think you could rather set attributes like this :
Try to make these modifications. If it still not working, you could add this inline after above code :
看来Chrome在媒体加载之前忽略了
muted
属性集。如果加载媒体并可以播放muted
属性,则可以自动播放视频,可以使用canplay
event侦听器检查。这样,您可以忽略设置
自动播放
和最初的属性
属性。It looks like Chrome is ignoring the
muted
attribute set before the media has loaded. The video is auto-played if themuted
attribute is set when the media is loaded and can be played, which can be checked with thecanplay
event listener.With this, you can ignore setting the
autoplay
andmuted
attributes initially.