无限视差滚动
无限视差滚动(轮播)可以给用户一种无限滚动的感觉,视觉效果非常的好。话不多说,先来看效果
这边因为得控制GIF图片大小在5MB以内,导致看着不太丝滑
这种效果在国外用得很多,不过最近几年国内也慢慢开始使用了,这只是演示效果,具体还得看实际要求。
接下来咱们来看代码部分
HTML结构的话 就是一个div即可
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><link rel="stylesheet" href="./src/css/视差滚动.css"><title>无限视差滚动</title>
</head>
<body><div class="container"></div>
</body>
<script src="./src/js/视察滚动.js"></script>
</html>
ok,接下来我们来看js代码部分
const imgs = ['./img/11.png','./img/22.jpg','./img/33.jpg','./img/44.jpg',// './img/55.jpg',]const container = document.querySelector('.container');let currentIndex = 0;function createItem(params) {const imgUrl = imgs[params];const item = document.createElement('div');item.classList.add('item');item.innerHTML = `<img src="${imgUrl}"/>`;container.appendChild(item);return item;}function reset() {container.innerHTML = '';const previousPage = currentIndex - 1 < 0 ? imgs.length - 1 : currentIndex - 1;const nextPage = currentIndex + 1 > imgs.length - 1 ? 0 : currentIndex + 1;createItem(previousPage).classList.add('previous')createItem(currentIndex).classList.add('current')createItem(nextPage).classList.add('next')}reset()let vitality = false;container.addEventListener('wheel', (event) => {if (!event.deltaY) {return}if (vitality) {return;}vitality = true;if (event.deltaY > 0) {// 往下滑container.classList.add('scroll-down');currentIndex = currentIndex + 1 > imgs.length - 1 ? 0 : currentIndex + 1;} else {// 往上滑container.classList.add('scroll-up');currentIndex = currentIndex - 1 > imgs.length - 1 ? 0 : currentIndex - 1;}});container.addEventListener('transitionend', () => {vitality = false;container.classList.remove('scroll-down');container.classList.remove('scroll-up');reset()})
核心代码咱都写好了,现在就是css样式部分来完善咱们得无限视差滚动(轮播)
* {margin: 0;padding: 0;box-sizing: border-box;}body {overflow: hidden;}.container {height: 100vh;position: relative;}.item {position: absolute;width: 100%;height: 100%;overflow: hidden;transition: 1s ease-in-out;}.item img {position: absolute;width: 100%;height: 100vh;object-fit: cover;transition: 1s;}.item.previous,.item.next {z-index: 1;height: 0;}.item.next {bottom: 0;}.item.next img {bottom: 0;transform: translateY(10%);}.item.item.previous img {transform: translateY(-10%);}.scroll-up .item.previous {height: 100%;}.scroll-up .item.previous img {transform: translateY(0%);}.scroll-up .item.current img {transform: translateY(10%);}.scroll-down .item.next {height: 100%;}.scroll-down .item.next img {transform: translateY(0%);}.scroll-down .item.current img {transform: translateY(-10%);}
这样下来,无限视差滚动(轮播)就已经完成了,是不是挺简单的。
希望这个小示列能帮助到你们。
- 失联
最后编辑时间 2024,05,11;17:38