为什么使用for循环只会执行一次而采用递归的方式就可以

 这里想实现一个外部元素带有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>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值