1、利用IntersectionObserver监听dom元素
<div class="box_over">
<ul>
<li v-for="(item,index) in 10" :style="`background:rgb(${255 * Math.random() * 2},${255 * Math.random() * 2},${255*Math.random() * 4})`">{{index}}</li>
</ul>
</div>
let observer = new IntersectionObserver((entries, observer) => {
entries.forEach(entry => {
// 当元素进入视口时
if (entry.isIntersecting) {
console.log("元素进入",entry.target.textContent)
entry.target.style.transform = "translateX(0px)";
entry.target.style.opacity = 1;
} else {
// 当元素离开视口时
let i = Math.floor(Math.random() * 2);
console.log(i)
console.log("元素消失",entry.target.textContent)
entry.target.style.transform = `translateX(${i?100:-100}px)`;
entry.target.style.opacity = 0;
}
});
}, {
rootMargin: '0px',
threshold: 0.1 // 你可以调整这个值来控制元素与视口的交叉程度
});
document.querySelectorAll("li").forEach((item) => {
observer.observe(item);
});
2、传统方式监听滚动条
let list = document.querySelectorAll("li");
document.querySelector(".box_over").onscroll = function (event){//记得给盒子box_over添加position:relative;样式,因为offsetTop是计算距离顶部父元素已定位的距离
list.forEach((item,index)=>{//对每个li标签都做了判断所以用了forEach循环
if(item.offsetTop - event.target.scrollTop < event.target.clientHeight && item.offsetTop + item.clientHeight > event.target.scrollTop){
console.log("元素进入",item.textContent)
item.style.transform = "translateY(0px)";
item.style.opacity = 1;
}else{
let i = Math.floor(Math.random() * 2);
item.style.transform = `translateY(${ 200}px)`;
item.style.opacity = 0;
}
})
}
标签:style,target,dom,元素,item,可视区,entry,Math,鼠标
From: https://www.cnblogs.com/jzm2842688813/p/18331962