<template>
<div class="test-con">
<div class="sticky-box">
<div class="box">
<div ref="box1">
<h1 ref="htitle1">hello</h1>
<h4>
乾坤空落落,岁月去堂堂。
末路惊风雨,穷边饱雪霜。
命随年欲尽,身与世俱忘。
无复屠苏梦,挑灯夜未央。
</h4>
</div>
</div>
</div>
<div class="sticky-box">
<div class="box">
<div ref="box2">
<h1 ref="htitle2">world</h1>
</div>
</div>
</div>
<div class="sticky-box">
<div class="box">
<div ref="box3">
<h1 ref="htitle3">html</h1>
</div>
</div>
</div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
<li>7</li>
<li>8</li>
<li>9</li>
<li>10</li>
</ul>
</div>
</template>
<script>
export default {
data() {
return {
h1FontSize: 50,
}
},
mounted() {
// 监听滚动事件,用handleScroll这个方法进行相应的处理
window.addEventListener("scroll", this.handleScroll);
},
unmounted() {
// 在组件生命周期结束的时候要销毁监听事件,否则其他页面也会使用这个监听事件
window.removeEventListener("scroll", this.handleScroll);
},
methods:{
// 页面滚动
handleScroll() {
this.$nextTick(()=>{
let scrollTop = document.body.scrollTop || document.documentElement.scrollTop || window.pageYOffset;
let clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
let n = scrollTop / 20;
if(scrollTop > clientHeight*1 && scrollTop < clientHeight*4) {
this.$refs.box1.style.display = 'block';
this.$refs.htitle1.style.fontSize = n + this.h1FontSize + 'px';
} else if (scrollTop > clientHeight*3) {
this.$refs.box1.style.display = 'none'
}
if(scrollTop > clientHeight*4 && scrollTop < clientHeight*8) {
this.$refs.box2.style.display = 'block';
this.$refs.htitle2.style.fontSize = scrollTop / 40 + this.h1FontSize + 'px';
} else {
this.$refs.box2.style.display = 'none'
}
if(scrollTop > clientHeight*8 && scrollTop < clientHeight*11) {
this.$refs.box3.style.display = 'block';
this.$refs.htitle3.style.fontSize = scrollTop / 40 + this.h1FontSize + 'px';
} else {
this.$refs.box3.style.display = 'none'
}
})
}
}
}
</script>
<style scoped lang="scss">
.sticky-box{
height: 400vh;
position: sticky;
top: 0;
.box{
height: 100vh;
position: sticky;
top: 0;
display: flex;
justify-content: center;
align-items: center;
h1{
font-size: 50px;
}
}
}
ul{
li{
height: 100px;
background-color: red;
margin: 20px 0;
}
}
</style>