原生JS实现下滑到当前模块时上滑淡入淡出

<!-- 确保有足够的空间可以滚动 -->  
<div style="height: 1000px;"></div>

<div class="about-certification-img" id="renzhengimg">
    <img src="https://img-operation.csdnimg.cn/csdn/silkroad/img/1722243038734.jpg" alt="">
  </div>
</div>
  
<!-- 确保有足够的空间可以滚动 -->  
<div style="height: 1000px;"></div>

<style>
    .about-certification-img {  
    transform: translateY(100%); /* 初始位置在视口下方 */  
    opacity: 0;  
    transition: transform 1s ease, opacity 1s ease; /* 平滑过渡效果 */  
    /* 其他样式,如宽度、背景等 */  
    width: 100%; /* 示例宽度 */  
    background-color: white; /* 示例背景色 */  
    padding: 20px; /* 示例内边距 */  
    box-sizing: border-box; /* 包括内边距和边框在内的总宽度 */  
}  
  
.visible {  
    transform: translateY(0); /* 滑到视口内 */  
    opacity: 1;  
}
</style>

<script>  
    // 节流函数  
    function throttle(func, limit) {  
        let lastFunc;  
        let lastRan;  
        return function() {  
            const context = this;  
            const args = arguments;  
            if (!lastRan) {  
                func.apply(context, args);  
                lastRan = Date.now();  
            } else {  
                clearTimeout(lastFunc);  
                lastFunc = setTimeout(function() {  
                    if ((Date.now() - lastRan) >= limit) {  
                        func.apply(context, args);  
                        lastRan = Date.now();  
                    }  
                }, limit - (Date.now() - lastRan));  
            }  
        };  
    }  
      
    function checkElementVisibility(element) {  
        var rect = element.getBoundingClientRect();  
        var viewHeight = window.innerHeight || document.documentElement.clientHeight;  
        var offset = 100; // 提前开始动画的偏移量  
      
        if (rect.top < viewHeight + offset) {  
            element.classList.add('visible');  
            element.classList.remove('hidden');  
        } else {  
            // 如果需要,可以在这里添加逻辑来移除 'visible' 类  
            // 当元素完全离开视口时  
        }  
    }  
      
    // 使用节流包装 checkElementVisibility  
    const throttledCheck = throttle(checkElementVisibility, 200); // 每200毫秒最多执行一次  
      
    document.addEventListener('scroll', function() {  
        var target = document.getElementById('renzhengimg');  
        if (target) {  
            throttledCheck(target);  
        }  
    });  
    </script>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值