关于video标签,手动刷新后不能自动播放问题

在使用js播放video时,会发先控制台会出现
play() failed because the user didn t interact with the document first的报错;
这是由于浏览器限制了,video标签非事件的自动播放。
不过,video标签可以设置autoplay属性

<video autoplay></video>//这种自动播放无效
<video autoplay muted></video>//需要设置muted,自动播放才能够生效

不过,当手动刷新页面后;发现自动播放,依旧失效了;于是,就需要通过js模拟点击事件去播放

//html 部分
<video autoplay id= video  src= xxxx ></video>
//js操作
const video = document.getElementById( video );
video.addEventListener( canplay ,canplay);
function canplay(){
  const a = document.createElement( a );
  a.onclick = function(){
       video .play();//这样就可以自动播放了
  },
  const event = new MouseEvent( click );
  a.dispatchEvent(event );
  video.removeEventListener( canplay ,canplay);
}

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容