水平滚动时为box动态添加/移除scroll类及类样式设置需求
实现水平滚动时动态添加/移除元素类名的方案
核心思路
通过监听容器的水平滚动事件,对比滚动前后的scrollLeft值判断滚动方向,动态给目标元素添加或移除scroll类,再通过CSS定义该类的图片样式。
完整代码实现
HTML结构
<!-- 横向滚动容器 --> <div class="scroll-container"> <!-- 目标元素 --> <div class="box"> <img src="your-image-url.jpg" alt="示例图片"> </div> <!-- 填充内容让容器支持横向滚动 --> <div class="filler-content"></div> </div>
CSS样式
/* 横向滚动容器基础样式 */ .scroll-container { width: 100%; overflow-x: auto; white-space: nowrap; padding: 20px 0; } /* box元素默认样式 */ .box { display: inline-block; margin: 0 20px; } .box img { width: 300px; height: auto; transition: all 0.3s ease; /* 样式变化过渡效果 */ } /* 滚动时的图片样式(可根据需求调整) */ .box.scroll img { transform: scale(1.1); opacity: 0.8; border-radius: 8px; } /* 填充内容,确保容器能横向滚动 */ .filler-content { display: inline-block; width: 1500px; height: 1px; }
JavaScript逻辑
const scrollContainer = document.querySelector('.scroll-container'); const box = document.querySelector('.box'); let prevScrollLeft = scrollContainer.scrollLeft; // 监听滚动事件,用防抖优化性能 scrollContainer.addEventListener('scroll', debounce(() => { const currentScrollLeft = scrollContainer.scrollLeft; // 对比滚动前后位置,判断方向并操作类名 if (currentScrollLeft > prevScrollLeft) { box.classList.add('scroll'); } else { box.classList.remove('scroll'); } // 更新滚动位置记录 prevScrollLeft = currentScrollLeft; }, 10)); // 防抖函数,避免频繁触发DOM操作 function debounce(func, delay) { let timer; return function() { clearTimeout(timer); timer = setTimeout(func, delay); } }
关键说明
- 防抖函数:减少滚动时的事件触发频率,避免不必要的DOM操作,提升页面流畅度
- 滚动方向判断:通过
scrollLeft的前后值对比,精准识别横向滚动/回滚动作 - 过渡效果:给图片添加
transition属性,让样式切换更平滑自然
内容的提问来源于stack exchange,提问作者jamal ahmad
相关产品推荐
相关产品推荐

