网页滚动到mySwiper时,启用gsap,固定轮播图,当切换完后,继续进行网页滚动
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Swiper demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1" />
<!-- Link Swiper's CSS -->
<link rel="stylesheet" href="../css/swiper-bundle.min.css" />
<!-- Demo styles -->
<style>
html,
body {
position: relative;
height: 100%;
}
body {
background: #eee;
font-family: Helvetica Neue, Helvetica, Arial, sans-serif;
font-size: 14px;
color: #000;
margin: 0;
padding: 0;
}
.swiper {
width: 100%;
height: 100%;
}
.swiper-slide {
text-align: center;
font-size: 18px;
background: #fff;
display: flex;
justify-content: center;
align-items: center;
}
.swiper-slide img {
display: block;
width: 100%;
height: 100%;
object-fit: cover;
}
</style>
</head>
<body>
<div style="background: #957444;height: 100vh;"></div>
<!-- Swiper -->
<div class="swiper mySwiper">
<div class="swiper-wrapper">
<div class="swiper-slide">Slide 1</div>
<div class="swiper-slide">Slide 2</div>
<div class="swiper-slide">Slide 3</div>
<div class="swiper-slide">Slide 4</div>
<div class="swiper-slide">Slide 5</div>
</div>
</div>
<div style="background: #000;height: 100vh;"></div>
<!-- Swiper JS -->
<script src="../js/swiper-bundle.min.js"></script>
<!-- Initialize Swiper -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/gsap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/ScrollTrigger.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.9.1/ScrollToPlugin.min.js"></script>
<script>
// 防抖函数
function debounce(func, wait) {
let timeout;
return function () {
const context = this;
const args = arguments;
clearTimeout(timeout);
timeout = setTimeout(function () {
func.apply(context, args);
}, wait);
};
}
// 初始化Swiper
var mySwiper = new Swiper(".mySwiper", {});
// 注册gsap插件
gsap.registerPlugin(ScrollTrigger);
let currentIndex = 0;
const totalImages = 5;
const vhUnit = window.innerHeight; // 获取视口高度
const endValue = totalImages * vhUnit;
// 创建防抖后的onUpdate函数
const debouncedOnUpdate = debounce(function (self) {
const progress = self.progress;
let newIndex = Math.floor(progress * totalImages);
newIndex = Math.min(newIndex, totalImages - 1);
newIndex = Math.max(newIndex, 0);
if (newIndex !== currentIndex) {
currentIndex = newIndex;
mySwiper.slideTo(currentIndex, 1000, false);
}
}, 100); // 100毫秒的延迟,可以根据需要调整
// 创建动画的时间轴,使用防抖后的onUpdate
ScrollTrigger.create({
trigger: ".mySwiper",
start: 'top top',
end: () => endValue,
pin: true,
scrub: true,
onUpdate: debouncedOnUpdate // 使用防抖后的onUpdate
});
</script>
</body>
</html>
参考:https://blog.csdn.net/weixin_60886119/article/details/133132345