ps: 先祝各位朋友新春快乐 ^o^/
想要首页不那么枯燥无味吗?还在未首页过于单调而苦恼吧,来试试这个吧(大佬请忽略上述语句·o·)
今天要实现一个页面线上渐变显示的效果,用来丰富首页等页面:
这里先随机建立几个模块:
<div id="app" style="height: 80vh;">
<div class="outter" >
<div v-for="item, index in partList" class="partDiv" :style="'background-color: rgb('+Math.ceil(Math.random()*255)+','+Math.ceil(Math.random()*255)+','+Math.ceil(Math.random()*255)+');'">
{{ index }}
</div>
</div>
</div>
当前效果:
接着为每个色块区域添加默认样式:
opacity: 0; // 默认透明
top: 50px; // 顶部距离
之后添加条件,当改色块触发到可视区域时展示:
mounted() {
this.scrollFun();
// 监听滚动
window.addEventListener('scroll', this.scrollFun, true);
},
data: function () {
return {
partList: [{},{},{},{},{},{},{},{},{},{}],
}
},
methods: {
scrollFun() {
let outter = document.querySelector('.outter')
let partDivList = document.querySelectorAll('.partDiv');
for(let i of partDivList) {
// 判断是否处于可视区域并更改样式
if(outter.scrollTop>=i.offsetTop-i.clientHeight ) {
i.style.opacity = 1;
i.style.top = 0;
};
}
}
}
最后添加动画即可:
transition: all 1s linear;
参考代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<!-- import CSS -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
</head>
<style scoped>
.partDiv {
width: 100%;
height: 500px;
position: relative;
opacity: 0;
top: 50px;
transition: all 1s linear;
}
.outter {
position: relative;
overflow-y: scroll;
height: 100%;
}
</style>
<div id="app" style="height: 80vh;">
<div class="outter" >
<div v-for="item, index in partList" class="partDiv" :style="'background-color: rgb('+Math.ceil(Math.random()*255)+','+Math.ceil(Math.random()*255)+','+Math.ceil(Math.random()*255)+');'">
{{ index }}
</div>
</div>
</div>
<script>
new Vue({
el: '#app',
mounted() {
this.scrollFun();
window.addEventListener('scroll', this.scrollFun, true);
},
data: function () {
return {
partList: [{},{},{},{},{},{},{},{},{},{}],
}
},
methods: {
scrollFun() {
let outter = document.querySelector('.outter')
let partDivList = document.querySelectorAll('.partDiv');
for(let i of partDivList) {
if(outter.scrollTop>=i.offsetTop-i.clientHeight ) {
i.style.opacity = 1;
i.style.top = 0;
};
}
}
}
})
</script>
</html>
希望本文会对您有所帮助~ ^_^