我的代码遇到问题。我想设置一个视频作为我的网站的背景。虽然代码在我的计算机上完美运行,但视频不会在我的手机上自动播放。相反,它会暂停,我必须手动点击屏幕才能启动视频。即使站点托管在 HTTPS 服务器上,此问题仍然存在。下面是我的代码。任何帮助将不胜感激 - 提前致谢!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Video Background</title>
<style>
html, body
{
margin: 0;
padding: 0;
height: 100%;
width: 100%;
overflow: hidden;
position: relative;
}
video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
z-index: -1;
}
</style>
</head>
<body>
<video id="background-video" autoplay muted playsinline>
<source src="background.mp4" type="video/mp4">
Your browser does not support the video tag.
</video>
<script>
function playVideo() {
var video = document.getElementById('background-video');
if (video) {
var playPromise = video.play();
if (playPromise !== undefined) {
playPromise.then(function() {
console.log('Video is playing');
}).catch(function(error) {
console.log('Video playback failed:', error);
});
}
}
}
function redirectToMenu() {
window.location.href = 'menu.html';
}
document.addEventListener('DOMContentLoaded', function() {
playVideo();
setTimeout(playVideo, 1000);
setTimeout(redirectToMenu, 9000);
});
document.addEventListener('click', function() {
playVideo();
});
</script>
</body>
</html>
使用静音属性
许多移动浏览器,包括 Safari 和 Chrome,不会自动播放有声视频。为了解决这个问题,您应该确保视频静音:
<video autoplay muted loop playsinline>
<source src="your-video.mp4" type="video/mp4">
</video>