一、设置自动播放video video标签设置默认图片

	<video controls="" preload="none" width="640" height="427" src="videoUrl">
         <source src="videoUrl" type="video/mp4">
    </video>
	var videos = document.querySelectorAll('video'); // 获取所有视频元素
    if (videos.length > 0) {
        videos.forEach((item) => {
          item.poster = 'img/default-poster.jpg';//设置默认图片
          item.muted = "true";//默认播放需要设置静音
        })
        videos[0].play(); // 播放第一个视频 默认播放前提需要设置视频静音 浏览器行为
    }

二、注意

video.play()出现以下情况:
Uncaught (in promise) DOMException: play() failed because the user didn’t interact with the document first.

Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first. 

问题原因:报错是由浏览器的自动播放策略引起的,现代浏览器通常会限制自动播放音视频以提升用户体验和节省带宽。设置一、中muted=true 静音效果即可解决

Logo

一站式 AI 云服务平台

更多推荐