来源:渡一前端
一、效果:
使用鼠标滚轮控制网页的图片上下切换,图片无限滚动,类似于轮播图
二、总体思路
1.要实现无限滚动,我们只需要考虑当前图片(cur)、上一张图片(pre)、下一张图片(next),后面均使用括号内容代替
2.动画使用过渡,将图片的高度从0变为100%
3.需要监听鼠标滚轮事件(wheel),根据返回的deltaY来判断鼠标滚轮的方向
4.需要监听过渡动画结束事件,来动态改变图片的样式
三、具体实现
由于我们需要考虑的三个图片元素是不停变化的,所以这里的图片元素,我们选择使用JS来动态生成,每张图片初始时的宽度需要撑满视口,初始时只显示当前图片,其他图片隐藏。这里使用CSS定位来完成,初始时cur高度为100vh,pre和next高度为0.pre定位在顶部,next定位在底部。根据鼠标滚轮的方向来重新生成这三个图片,同时将pre或next的高度变为100%
1.目录
2.html
<!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>
</head>
<body>
<div class="scroll-container"></div>
</body>
<script src="./index.js"></script>
<style>
* {
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
overflow: hidden;
}
.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 ease-in-out;
}
.scroll-container {
height: 100vh;
position: relative;
}
.item.pre,
.item.next {
z-index: 1;
height: 0;
}
.item.pre {
top: 0;
}
.item.next {
bottom: 0
}
.item.pre img {
transform: translateY(-10%);
}
.item.next img {
bottom: 0;
transform: translateY(10%);
}
.scroll-up .pre,
.scroll-down .next {
height: 100%;
}
.scroll-up .pre img {
transform: translateY(0);
}
.scroll-up .cur img {
transform: translateY(10%);
}
.scroll-down .next img {
transform: translateY(0);
}
.scroll-down .cur img {
transform: translateY(-10%);
}
</style>
</html>
3.js
const imgs = ['./assets/1.jpg', './assets/2.png', './assets/3.jpg']
let currentIndex = 0
const scrollContainer = document.querySelector('.scroll-container')
function creatItem(index) {
let imgUrl = imgs[index]
const item = document.createElement('div')
item.classList.add('item')
item.innerHTML = `<img src=${imgUrl} />`
scrollContainer.appendChild(item)
return item
}
function init() {
scrollContainer.innerHTML = ''
let preIndex = currentIndex - 1 < 0 ? imgs.length - 1 : currentIndex - 1
let nextIndex = currentIndex + 1 > imgs.length - 1 ? 0 : currentIndex + 1
creatItem(preIndex).classList.add('pre')
creatItem(currentIndex).classList.add('cur')
creatItem(nextIndex).classList.add('next')
}
init()
let isAnimation = false
scrollContainer.addEventListener('wheel', (e) => {
if ((e.deltaY = 0)) {
return
}
if (isAnimation) {
return
}
isAnimation = true
if (e.deltaY > 0) {
//向下滚动
scrollContainer.classList.add('scroll-down')
currentIndex = currentIndex + 1 > imgs.length - 1 ? 0 : currentIndex + 1
} else {
//向上滚动
scrollContainer.classList.add('scroll-up')
currentIndex = currentIndex - 1 < 0 ? imgs.length - 1 : currentIndex - 1
}
})
scrollContainer.addEventListener('transitionend', (e) => {
isAnimation = false
scrollContainer.classList.remove('scroll-up')
scrollContainer.classList.remove('scroll-down')
init()
})