这里想实现一个外部元素带有animate-box的类名时,给其内部的含有ant类名的元素加上动画效果,但用for循环给带有ant类名的元素设置动画类名时发现只有第一个元素会加上,不太理解为什么会这样,为什么用递归的方式实现就可以呢?
watch.js:
import $ from 'jquery';
// 给每个加了ant类名的元素加上动画效果
const addAnimateForAnt = (target, child, classname)=>{
const childList = target.find(child);
const len = childList.length;
// console.log('len', len);
// 为什么这种方式无法让所有元素都加上ant-in的类名,而下面那种方式就可以
// let timer = null;
// for(var i=0; i<len; i++){
// if(i==0){
// $(childList[i]).addClass(classname);
// }else{
// if(timer) clearTimeout(timer);
// timer = setTimeout(()=>{
// $(childList[i]).addClass(classname);
// }, 200)
// }
// }
const addAntClass = (target, len, cur)=>{
if(cur <= len){
if(cur == 1){
$(target[cur-1]).addClass(classname);
addAntClass(target, len, cur+1);
}else{
setTimeout(()=>{
$(target[cur-1]).addClass(classname);
addAntClass(target, len, cur+1);
}, 200)
}
}
}
addAntClass(childList, len, 1);
}
// 监听加了animate-box类名的元素,出现在视野中时加上动画效果
export const watchDom = () => {
var timer = setInterval(() => {
const boxs = document.querySelectorAll(".animate-box");
const observer = new IntersectionObserver((entries) => {
console.log('entries', entries);
entries.forEach((entry)=>{
if(entry.isIntersecting){
// 给类名为animate-box的下面加了ant类名的每个元素加上动画
addAnimateForAnt($(entry.target), '.ant', 'ant-in');
}
})
});
boxs.forEach((item) => {
observer.observe(item);
});
clearInterval(timer);
}, 100);
};
watchDom();
index.vue:
<template>
<div class="animate-box">
<div v-for="item in list" :key="item.id" class="item ant">{{ item.name }}</div>
</div>
</template>
<script lang='ts' setup>
const list = [
{
id: 1,
name: 111,
},
{
id: 2,
name: 222,
},
{
id: 3,
name: 333,
},
{
id: 4,
name: 444,
},
{
id: 5,
name: 555,
},
{
id: 6,
name: 666,
},
{
id: 7,
name: 777,
},
{
id: 8,
name: 888,
},
]
</script>
<style scoped lang='scss'>
.item {
border: 1px solid #333;
padding: 80px;
margin-bottom: 20px;
}
</style>