前言
最近在挑选手机,发现一加手机官网有一个神奇的功能,滚动条明明在向下滚动,页面却在横向移动,这也太神奇了叭!
写toB项目太久,增删改查表格写的都快麻了,看到这么神奇的功能手痒,今天就自己实现一个。
原理
主要依赖以下css
- position: sticky;
- transform: translate;
画了一张原理图
主要代码
<div class="content fcenter">上面的内容</div>
<div id="scroll" class="scroll">
<div class="sticky">
<div id="scrollBox" class="scroll-box">
<div class="scroll-item fcenter">1</div>
<div class="scroll-item fcenter">2</div>
<div class="scroll-item fcenter">3</div>
</div>
</div>
</div>
<div class="content fcenter">下面的内容</div>
.fcenter {
display: flex;
align-items: center;
justify-content: center;
}
.content {
width: calc(100vw - 18px);
height: 100vh;
background: #b9f5e0;
}
.scroll {
position: relative;
width: calc(100vw - 18px);
}
.sticky {
position: sticky;
top: 0;
overflow: hidden;
}
.scroll-box {
display: flex;
}
.scroll-item:nth-child(1) {
background: #f6a2a2;
}
.scroll-item:nth-child(2) {
background: #d1d1ff;
}
.scroll-item:nth-child(3) {
background: #efefc3;
}
.scroll-item {
width: calc(100vw - 18px);
height: 100vh;
flex-shrink: 0;
}
const scroll = document.getElementById('scroll')
const scrollBox = document.getElementById('scrollBox')
const vw = document.body.clientWidth // 不包含滚动条的宽度
const vh = window.innerHeight
// 这里的高度设置为 length-1 个横向块 + 屏幕高度
// 因为最后一块,滚动的距离并不是宽度,而是高度
sHeight = vw * (scrollBox.children.length - 1) + vh
scroll.style.height = sHeight + 'px'
window.addEventListener('scroll', () => {
// 获取scroll的位置信息
const {top, bottom} = scroll.getBoundingClientRect();
// top <= 0 时,代表容器元素到达视图顶部。
if (top <= 0 && top > -vw * 2) {
scrollBox.style.transform = `translateX(${top}px)`
}
if (top > 0) {
scrollBox.style.transform = `translateX(0px)`
}
if (top < -vw * 2) {
scrollBox.style.transform = `translateX(-${sHeight-vh}px)`
}
});
在线示例
总结
以上就是实现滚动条向下滚动,网页却横向移动的方法啦!
说真的,写这种东西才有写前端的感觉,充满了奇思妙想。
我是一个在前端已死的时代,不断在内卷中苦苦挣扎的大专生——天铭,希望和大家共同努力,只要我们足够努力,我们的老板就能早日过上自己想要的日子!