效果如下:
1,准备结构
<div id="root">
<div ref="container" id="container" @mousewheel="scrollDirection">
<div class="page page1" :style="{width: screenWidth+'px',height: screenHeight+'px'}">page 1</div>
<div class="page page2" :style="{width: screenWidth+'px',height: screenHeight+'px'}">page 2</div>
<div class="page page3" :style="{width: screenWidth+'px',height: screenHeight+'px'}">page 3</div>
<div class="page page4" :style="{width: screenWidth+'px',height: screenHeight+'px'}">page 4</div>
</div>
</div>
2,设置必要样式(缺一不可)
#container {
overflow: hidden;
height: 100vh;
}
.page {
position: relative;
transition: all 1s ease;
top: 0;
}
3,初始化,定义数据,获取屏幕宽高,总页数
data() {
return {
screenWidth: 0,
screenHeight: 0,
totalPage: 0,
currentPage: 0,
isScrolling: false,
};
},
mounted() {
this.screenWidth = this.$refs.container.clientWidth;
this.screenHeight = this.$refs.container.clientHeight;
this.totalPage = this.$refs.container.children.length;
window.addEventListener('resize', () => {
this.screenWidth = this.$refs.container.clientWidth;
this.screenHeight = this.$refs.container.clientHeight;
this.scrollFn(this.currentPage)
})
},
当屏幕尺寸变化时重新获取容器宽度(注意要使用clientWidth,clientHeight)
4,容器监听到滚轮变化时,首先判断其滚动方向,再控制当前页数,调取滚动函数(可传滚动速度,这里省略了)
// 判断滚轮方向
scrollDirection(e) {
if (!this.isScrolling) {
if (e.deltaY > 0) {
//滚轮下滑
this.currentPage++;
if (this.currentPage > this.totalPage - 1) {
return (this.currentPage = this.totalPage - 1);
}
this.scrollFn(this.currentPage);
} else {
// 滚轮上滑
this.currentPage--;
if (this.currentPage < 0) {
return (this.currentPage = 0);
}
this.scrollFn(this.currentPage);
}
}
},
// 滚动控制
scrollFn(page, speed = 0.5) {
let pages = document.querySelectorAll(".page");
let that = this;
pages.forEach(item => {
item.style.transition = `all ${speed}s ease`;
item.style.top = -that.screenHeight * page + "px";
});
this.isScrolling = true;
setTimeout(() => {
this.isScrolling = false;
},speed*1000)
},
isScrolling相当于节流,不至于出现连续滚动。