纯css极致视觉差借鉴于 原神官网

86 阅读1分钟

sherlockkid7 改自此作者

  1. 静态页面给与三个div盒子100vh高度background-attachment设置为fixed ,让背景相对于视口固定,随着鼠标滚动,背景也不会随着页面而滚动
  2. js中监听滚动条事件,事件触发获取滚动条偏移量,根据偏移量去添加class属性是中间文字出现动画,偏移量除以视口高度用来确定处于哪个背景盒子位置触发当前背景盒子下方的文字,当上下触底移出class
const bodyBox = document.body
const htmlBox = document.querySelector('html')
const txts = document.querySelectorAll('.txt-content')
const clientHeight = document.documentElement.clientHeight
function fn(){
    let timer;
    if(timer)return
    timer = setTimeout(() => {
        const {scrollTop} = htmlBox
        const step = Math.floor(scrollTop/clientHeight)
        const height = txts[0].offsetHeight
        if(scrollTop-step*clientHeight>height && step<txts.length){
            txts[step].classList.add('scroll')
        }else if(scrollTop>=bodyBox.offsetHeight-clientHeight || scrollTop==0){
            for (let i = 0; i < txts.length; i++) {
                txts[i].classList.remove('scroll')
            }
        }
        timer = null
    }, 500);
}
window.addEventListener('scroll',fn)

附上代码 code.juejin.cn/pen/7291105…