html5 实现视频播放
常用属性
- controls: 显示默认的播放控制条。
- autoplay: 页面加载时自动播放视频。
- loop: 视频播放结束后自动重新播放。
- muted: 静音播放视频。
- poster: 在视频加载前显示的预览图。
例子:
<video src="my_video_file.mp4" controls autoplay loop muted poster="review.jpg"></video>
一、实现视频循环播放:
loop属性确保视频循环播放
autoplay属性使视频在页面加载时自动播放
muted属性则静音播放,避免自动播放视频时的声音干扰
<video class="video_box" loop autoplay muted>
<source src="my_video_file.mp4" type="video/mp4">
<span>This video browser does not support</span>
</video>
二、使用JavaScript控制视频播放
1、通过监听视频的ended事件,在视频播放结束时重新播放
<video id="myVideo">
<source src="my_video_file.mp4" type="video/mp4">
<span>This video browser does not support</span>
</video>
<script>
const myVideo = document.getElementById('myVideo');
myVideo.addEventListener('ended', () => {
myVideo.play();
});
</script>
2、通过检查视频的currentTime属性,实现更精细的控制
<video id="myVideo">
<source src="my_video_file.mp4" type="video/mp4">
<span>This video browser does not support</span>
</video>
<script>
const myVideo = document.getElementById('myVideo');
myVideo.addEventListener('timeupdate', () => {
if (myVideo.currentTime >= myVideo.duration - 0.2) {
myVideo.currentTime = 0;
myVideo.play();
}
});
</script>
三、css动画加JavaScript控制视频效果
<style>
.video_fade_in {animation: fadeIn 2s;}
.video_fade_out {animation: fadeOut 2s;}
@keyframes fadeIn {from { opacity: 0; }to { opacity: 1; }}
@keyframes fadeOut {from { opacity: 1; }to { opacity: 0; }}
</style>
<video class="video_fade_in">
<source src="my_video_file.mp4" type="video/mp4">
<span>This video browser does not support</span>
</video>
<video id="myVideo" class="video_fade_out">
<source src="my_video_file.mp4" type="video/mp4">
<span>This video browser does not support</span>
</video>
<!-- 在视频播放结束后淡入淡出 -->
<script>
const myVideo = document.getElementById('myVideo');
myVideo.addEventListener('ended', () => {
myVideo.classList.add('video_fade_out');
setTimeout(() => {
myVideo.classList.remove('video_fade_out');
myVideo.currentTime = 0;
myVideo.play();
}, 2000);
});
</script>