效果示例图
示例代码
<template>
<div class="animation-wrap">
<!-- header-start -->
<div class="animation-header">头部</div>
<!-- header-end -->
<div class="animation-subtitle animation-show">标题一</div>
<div class="animation-content animation-show">内容一</div>
<div class="animation-subtitle animation-show">标题二</div>
<div class="animation-content animation-show">内容二</div>
<div class="animation-subtitle animation-show">标题三</div>
<div class="animation-content animation-show">内容三</div>
<div class="animation-subtitle animation-show">标题四</div>
<div class="animation-content animation-show">内容四</div>
<div class="animation-subtitle animation-show">标题五</div>
<div class="animation-content animation-show">内容五</div>
<!-- footer-start -->
<div class="animation-footer">底部</div>
<!-- footer-end -->
</div>
</template>
<script>
export default {
data() {
return {};
},
created() {},
mounted() {
/**
* 监听滚动条事件
* **/
this.scrollHandle();
window.addEventListener('scroll', this.scrollHandle);
},
methods: {
scrollHandle() {
//可视窗口的高度
const viewPortHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
console.log('[可视窗口的高度]', viewPortHeight);
//滚动条距离顶部的距离
const scrollTop = this.getScrollTop();
console.log('[滚动条距离顶部的距离]', scrollTop);
const elHander = document.querySelectorAll('.animation-show');
elHander.forEach(el => {
const offsetTop = el.offsetTop;
console.log('[每个节点距离顶部的距离]', offsetTop);
//当节点距离顶部的距离-滚动条距离顶部的距离小于窗口可视高度时,说明节点已经出现在用户的视线里
console.log('[]', offsetTop - scrollTop <= viewPortHeight);
if (offsetTop - scrollTop <= viewPortHeight) {
el.classList.add('current-animation');
} else {
el.classList.remove('current-animation');
}
});
},
/**
* 获取滚动条距离顶部的距离
* **/
getScrollTop() {
let scrollTop = 0;
//documentElement:文档的文档元素
if (document.documentElement && document.documentElement.scrollTop) {
scrollTop = document.documentElement.scrollTop;
} else if (document.body) {
scrollTop = document.body.scrollTop;
}
return scrollTop;
}
}
};
</script>
<style lang="scss" scoped>
.animation-wrap {
width: 1200px;
margin: 0px auto;
.animation-header {
width: 100%;
height: 300px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
}
.animation-footer {
width: 100%;
height: 300px;
margin-top: 12px;
background-color: red;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
}
.animation-subtitle {
width: 100%;
height: 50px;
display: flex;
align-items: center;
margin: 12px auto;
background-color: powderblue;
color: #fff;
padding-left: 12px;
}
.animation-content {
width: 100%;
height: 400px;
display: flex;
justify-content: center;
align-items: center;
color: #fff;
background-color: #dcdcdc;
}
.current-animation {
animation: myfirst 2s ease;
}
@keyframes myfirst {
0% {
transform: translate(0%, 200%) scale(0);
}
100% {
transform: translate(0px, 0px) scale(1);
}
}
}
</style>