源码在最后面 好像有些浏览器不适配(可能是设置了禁用自动播放的功能)
实现功能
- 视频自动无声播放
- 鼠标置于某个视频板块之上时自动无声播放
- 点击视频跳转视频链接
效果图(部分 视频加载可能有点慢)
部分功能实现原理
1.无声播放 (Muted Playback)
无声播放是指在播放媒体文件时不播放任何音频。在HTML5中,可以通过<audio>或<video>标签的muted属性来实现这一功能。
<video src="myVideo.mp4" controls muted></video>
2.自动播放 (Autoplay)
自动播放是指在页面加载后立即开始播放媒体文件,无需用户点击播放按钮。为了提高用户体验并遵守浏览器的安全策略,不同的浏览器对自动播放有不同的限制。在有些情况下,自动播放是被禁用的。
<video src="myVideo.mp4" autoplay controls></video>
当然也可以使用JavaScript来动态设置这些属性
const video =document.querySelector('video');
video.muted = true; //设置静音播放为真
video.autoplay = true; //设置自动播放为真
video.play();
完整源代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>XX视频网站</title>
<style>
body {
font-family: 'Microsoft JhengHei', sans-serif;
margin: 0;
padding: 0;
background-color: #f0f0f0;
}
.top-bar {
background-color: red;
color: white;
text-align: center;
padding: 20px 0;
font-size: 24px;
font-weight: bold;
}
.video-grid {
display: flex;
justify-content: center;
flex-wrap: wrap;
gap: 20px;
padding: 20px;
}
.video-item {
position: relative;
width: calc(33.33% - 20px);
height: 0;
padding-bottom: 56.25%;
box-shadow: 0 4px 8px rgba(0,0,0,0.1);
overflow: hidden;
cursor: pointer;
transition: transform 0.3s ease-in-out;
}
.video-item:hover {
transform: translateY(-10px);
}
.video-item video {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
object-fit: cover;
z-index: 1;
}
.video-title {
position: absolute;
bottom: 0;
left: 0;
width: 100%;
background-color: rgba(0,0,0,0.5);
color: white;
font-size: 18px;
font-weight: bold;
padding: 10px;
box-sizing: border-box;
z-index: 2;
}
</style>
</head>
<body>
<div class="top-bar">XX视频网站</div>
<div class="video-grid">
<div class="video-item" onclick="location.href='https://www.w3schools.com/html/mov_bbb.mp4';">
<video src="https://www.w3schools.com/html/mov_bbb.mp4" autoplay loop muted></video>
<div class="video-title">快乐小视频 1</div>
</div>
<div class="video-item" onclick="location.href='https://www.w3schools.com/html/mov_bbb.mp4';">
<video src="https://www.w3schools.com/html/mov_bbb.mp4" autoplay loop muted></video>
<div class="video-title">快乐小视频 2</div>
</div>
<div class="video-item" onclick="location.href='https://www.w3schools.com/html/mov_bbb.mp4';">
<video src="https://www.w3schools.com/html/mov_bbb.mp4" autoplay loop muted></video>
<div class="video-title">快乐小视频 3</div>
</div>
<!-- 更多行可以按照上面的模式重复 -->
</div>
<script>
// 模拟鼠标悬停播放效果
document.querySelectorAll('.video-item').forEach(item => {
item.addEventListener('mouseover', () => {
item.querySelector('video').play();
});
item.addEventListener('mouseout', () => {
item.querySelector('video').pause();
});
});
</script>
</body>
</html>