首先上面的效果不单单是视频播放,而是通过滚动条的下拉实现的动效。起初想的是通过很多张图片,每次下拉滚动条时就遍历加载不同的图片。但是参考上面的网址后,发现人家只是引入了一个视频,并没有搞很多图片、,于是自己也想方设法尝试实现。
👍scrollTrigger实现
如何通过js实现:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>控制视频指定帧</title>
<style>
body {
margin: 0;
height: 400vh;
}
.video-box {
margin-top: 100vh;
width: 100%;
position: sticky;
top: 0;
}
video {
width: 100%;
display: block;
}
</style>
</head>
<body>
<div class="video-box">
<video id="video">
<!-- 链接视频可能会出现卡顿情况,本地引入视频则不会 -->
<source src="https://res.cloudinary.com/mkpill/video/upload/v1691752608/launch_pill_795f2be8d2.mp4" type="video/mp4" />
</video>
</div>
</body>
<script>
let showPlan = 0; //模块显示的完成比
let videoTime = 6; //引入视频的时间,此完整视频全长为6s
let deviation = window.innerHeight; //模块显示偏差率 单位 px ,值越大看到模块时动起来越晚
const videoBox = document.querySelector('.video-box')
const video = document.getElementById('video')
const rect = videoBox.getBoundingClientRect()
function update() {
const { bottom, top, height } = rect
const scrollTop = window.pageYOffset; //滚动条距离顶部高度
//滚动条距离顶部高度 - (容器距离顶部 - 可视窗口) = 容器显示出来的位置
const boxPosition = scrollTop - (top - window.innerHeight)
if (boxPosition <= 0) return //未达到可视位置时不执行以下
showPlan = (boxPosition - deviation) / height * videoTime
if (showPlan < videoTime) {
videoBox.style.position = 'sticky'
videoBox.style.top = 0
video.currentTime = showPlan.toFixed(2)
} else {
videoBox.style.position = 'relative'
videoBox.style.top = height + 'px'
}
};
// 滚轮监听
window.addEventListener('scroll', function () {
update()
})
</script>
</html>