如何使用纯JavaScript实现页面滚动时Div元素宽度递增效果?
实现滚动时Div宽度动态增加的纯JS方案
嘿,这个滚动触发宽度变化的效果很容易用纯JavaScript实现,结合你现有的HTML和CSS结构,我给你整理了完整的解决方案:
完整代码示例
HTML(保留你的原有结构)
<div class="about"> <div class="container"> <h6 class="font_caps">/ Introduction</h6> <h2 class="lead">Accelerating Global Brands — Years ahead.</h2> <p class="lead">We are a world—class team of industry—leading professionals, who constantly push new technology to its limits.</p> </div> </div>
CSS(你的现有代码,transition是平滑动画的关键)
.about { overflow: hidden; z-index: 2; width: 50%; height: 100vh; display: flex; padding: 10vw 0; margin: 0 auto; background: url('./img/pexels-alesia-kozik-5989895.jpg') no-repeat; transition: width .5s; /* 靠这个属性实现宽度变化的平滑过渡 */ }
JavaScript 核心逻辑
// 获取目标元素 const aboutSection = document.querySelector('.about'); // 定义初始宽度和目标宽度(百分比) const initialWidth = 50; const targetWidth = 100; // 设置滚动阈值:滚动1.5倍视口高度后停止宽度增长,可按需调整 const scrollThreshold = window.innerHeight * 1.5; // 防抖函数优化性能(避免scroll事件高频触发导致卡顿) function debounce(func, delay = 10) { let timeoutId; return (...args) => { clearTimeout(timeoutId); timeoutId = setTimeout(() => func.apply(this, args), delay); }; } // 处理滚动逻辑的核心函数 function handleScroll() { // 获取当前滚动距离 const scrollTop = window.scrollY; // 计算宽度变化比例:滚动距离/阈值,最大不超过1(防止宽度超过目标值) const widthRatio = Math.min(scrollTop / scrollThreshold, 1); // 计算当前应设置的宽度值 const currentWidth = initialWidth + (targetWidth - initialWidth) * widthRatio; // 给元素设置宽度 aboutSection.style.width = `${currentWidth}%`; } // 给窗口添加滚动监听,用防抖包装减少函数执行次数 window.addEventListener('scroll', debounce(handleScroll)); // 页面加载时执行一次,确保初始状态正确 handleScroll();
关键逻辑说明
- 滚动阈值调整:我设置的
1.5倍视口高度是宽度从50%到100%的滚动触发范围,你可以根据需求修改——比如改成window.innerHeight就是滚动一屏后宽度达到最大值,或者更大的数值让宽度变化过程更长。 - 防抖优化:scroll事件在滚动时会每秒触发几十次,用防抖函数可以合并多次触发,避免页面卡顿。
- CSS过渡配合:你已经给
.about加了transition: width .5s,所以JS只需要修改width属性,CSS会自动处理平滑动画,不用手动写JS动画,既简单又高效。 - 边界控制:用
Math.min确保宽度比例不会超过1,这样宽度最多增长到目标值(比如100%),不会无限变大。
如果想让宽度变化在滚动到特定位置才开始,比如滚动200px后再触发,只需要在handleScroll里加个判断:
if (scrollTop < 200) { aboutSection.style.width = `${initialWidth}%`; return; } // 后面再执行原有的宽度计算逻辑
内容的提问来源于stack exchange,提问作者Mahmoud Kattan
相关产品推荐
相关产品推荐

