jQuery实现图片横向滚动到边界停止 避免右侧出现空隙问题求助
问题原因
- 现有滚动逻辑固定每次移动单张图片的宽度,当右侧剩余可滚动距离小于单图宽度时,滚动后会超出有效内容范围,从而出现空隙
- 原代码中边界判断逻辑为空,未对极限滚动位置做兜底限制
修复后代码
// 缓存DOM对象避免重复查询,提升性能 const $imgContainer = $('.img-container') const imgWidth = $('.images').width() const $leftBtn = $('#left-scroll') const $rightBtn = $('#right-scroll') // 初始化页面时就检查边界状态 checkScroll() function checkScroll() { const scrollLeftPosition = $imgContainer.scrollLeft() const maximumScroll = $imgContainer.prop('scrollWidth') - $imgContainer[0].offsetWidth // 根据当前滚动位置自动切换按钮显隐 $leftBtn.toggle(scrollLeftPosition > 0) $rightBtn.toggle(scrollLeftPosition < maximumScroll) } $('#left-scroll').click(function() { const scrollLeftPosition = $imgContainer.scrollLeft() // 向左滚动时取单图宽度、已滚动距离的较小值,避免超出左边界 const realScrollStep = Math.min(imgWidth, scrollLeftPosition) $imgContainer.animate( {scrollLeft: `-=${realScrollStep}px`}, "fast", checkScroll ); }); $('#right-scroll').click(function() { const scrollLeftPosition = $imgContainer.scrollLeft() const maximumScroll = $imgContainer.prop('scrollWidth') - $imgContainer[0].offsetWidth const remainingScroll = maximumScroll - scrollLeftPosition // 向右滚动时取单图宽度、剩余可滚动距离的较小值,避免超出右边界出现空隙 const realScrollStep = Math.min(imgWidth, remainingScroll) $imgContainer.animate( {scrollLeft: `+=${realScrollStep}px`}, "fast", checkScroll ); });
说明
- 调整了变量命名避免逻辑歧义,统一缓存高频使用的DOM节点,减少重复查询开销
- 滚动步长改为动态计算,永远不会超过当前可滚动的最大范围,滚动后可自然对齐边框不会出现空隙
- 补充了初始化边界检查逻辑,页面加载后即可根据当前内容状态自动隐藏对应边界按钮
内容的提问来源于stack exchange,提问作者JFeel
相关产品推荐
相关产品推荐

