vue如何判断组件进入可视区域
作者:文i
这篇文章主要介绍了vue如何判断组件进入可视区域问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
vue判断组件进入可视区域
1、mounted 监听 监听元素是否进入/移出可视区域
window.addEventListener("scroll", this.scrollHandle, true); // 监听 监听元素是否进入/移出可视区域
2、 methods 执行事件
scrollHandle() { const offset = this.$el.getBoundingClientRect(); const offsetTop = offset.top; const offsetBottom = offset.bottom; // const offsetHeight = offset.height; // 进入可视区域 // console.log(offsetTop,offsetBottom) if (offsetTop <= window.innerHeight && offsetBottom >= 0) { // console.log('进入可视区域'); } else { // console.log('移出可视区域'); } }
3、记得在适当的时候移除事件监听
window.removeEventListener('scroll', this.scrollHandle, true);
vue判断组件是否出现在可视区,使用动画
<div class="real-time-data"> <h1 class="title">实时招生数据</h1> <div class="detail">结合三大平台考生行为数据,为入驻高校实时分析当前报考情况,并精准预测当年招生趋势</div> <div class="img-box p-relative "> <img src="@/assets/images/edudata-h5/real-time-data-bg1.webp" alt="" class="bg1"> <img src="@/assets/images/edudata-h5/real-time-data-bg2.webp" alt="" class="bg2 p-absolute" :class="isShowAnimation ? 'img-showBigL' :''"> <img src="@/assets/images/edudata-h5/real-time-data-bg3.webp" alt="" class="bg3 p-absolute" :class="isShowAnimation ? 'img-showBigR' :''"> <img src="@/assets/images/edudata-h5/real-time-data-bg4.webp" alt="" class="bg4 p-absolute" :class="isShowAnimation ? 'img-showBigL' :''"> </div> </div>
export default { data() { return { isShowAnimation: false } }, mounted() { window.addEventListener("scroll", this.scrollHandle, true); // 监听 监听元素是否进入/移出可视区域 }, methods: { scrollHandle() { const offset = this.$el.getBoundingClientRect(); const offsetTop = offset.top; const offsetBottom = offset.bottom; // const offsetHeight = offset.height; // 进入可视区域 // console.log(offsetTop,offsetBottom) if (offsetTop <= window.innerHeight && offsetBottom >= 0) { // console.log('进入可视区域'); this.isShowAnimation = true } else { this.isShowAnimation = false // console.log('移出可视区域'); } } } }
//动画 .img-showBigL { animation: fadeinShowL 1.5s forwards } .img-showBigR { animation: fadeinShowR 1.5s forwards } @keyframes fadeinShowL { 0% { opacity: 0; transform: translate(100px, 0) scale(0.5); } ; 100% { opacity: 1; transform: translate(0px, 0) scale(1); } } @keyframes fadeinShowR { 0% { opacity: 0; transform: translate(-100px, 0) scale(0.5); } ; 100% { opacity: 1; transform: translate(0px, 0) scale(1); } }
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。