本文主要是介绍原生JS实现下滑到当前模块时,上浮显示,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
源码:
<div style="height: 1000px;"></div>
<!-- 图 -->
<div class="yingxiao-box"><div id="yingxiaoimg" class="yingxiao-img"><imgsrc="https://alp.alicdn.com/1703175009746-2100-220.png"alt=""></div>
</div>
<style>.yingxiao-img {text-align: center;transform: translateY(100%);/* 初始位置在视口下方 */opacity: 0;transition: transform 1s ease, opacity 1s ease;/* 平滑过渡效果 */}.visible {transform: translateY(0);/* 滑到视口内 */opacity: 1;}</style>
<script>// 节流函数 function throttle2(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 checkElementVisibility2(element) {var rect = element.getBoundingClientRect();var viewHeight = window.innerHeight || document.documentElement.clientHeight;var offset = 500; // 提前开始动画的偏移量 if (rect.top < viewHeight + offset) {element.classList.add('visible');element.classList.remove('hidden');} else {// 如果需要,可以在这里添加逻辑来移除 'visible' 类 // 当元素完全离开视口时 }}// 使用节流包装 checkElementVisibility const throttledCheck2 = throttle2(checkElementVisibility2, 200); // 每200毫秒最多执行一次 document.addEventListener('scroll', function () {var target = document.getElementById('yingxiaoimg');if (target) {throttledCheck2(target);}});
</script>
这篇关于原生JS实现下滑到当前模块时,上浮显示的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!