smoothScrolling函数失效原因排查及修复求助
垂直平滑滚动滑块修复方案
问题原因
你的代码存在三个核心问题导致滚动功能失效:
- 容器高度计算错误:
.container设置了height:100%,导致.scrollable的高度被限制在100vh范围内,init()方法给body设置的高度同样为100vh,页面没有足够的滚动长度触发滚动行为。 - 滚动元素样式缺失:
.scrollable没有明确的样式规则让它的高度由子元素撑开,无法形成有效的滚动范围。 - 图片样式未生效:CSS中定义了
.img类,但HTML里的img标签未添加该class(不影响滚动功能,但会影响图片显示效果)。
修复步骤
- 移除
.container的height:100%规则,让容器高度由内部6个.image-container(每个占100vh高度)自动撑开,此时.scrollable的高度会变为600vh,body设置该高度后即可正常滚动。 - 给HTML中的所有img标签添加
class="img",应用预设的图片样式。 - (可选)给
.scrollable添加will-change: transform属性,提升动画渲染性能。
修复后的完整代码
JavaScript
const scrollable = document.querySelector('.scrollable'); let current = 0; let target = 0; let ease = 0.075; // 线性插值实现平滑过渡 function lerp(start, end, t) { return start * (1 - t) + end * t; } function init() { document.body.style.height = `${scrollable.getBoundingClientRect().height}px`; } function smoothScroll() { target = window.scrollY; current = lerp(current, target, ease); scrollable.style.transform = `translate3d(0, ${-current}px, 0)`; requestAnimationFrame(smoothScroll) } init() smoothScroll()
CSS
*{ margin: 0; padding: 0; box-sizing: border-box; } body, html { overscroll-behavior: none; background: black; height: 100vh; width: 100%; } main { position: fixed; width: 100%; height: 100vh; } .scrollable { will-change: transform; /* 提升动画性能 */ } .container { /* 移除height:100%,让高度由子元素自动撑开 */ } .image-container { position: relative; width: 100%; height: 100vh; /* 明确每个容器占满视口高度 */ overflow: hidden; display: flex; align-items: center; justify-content: center; } h1 { position: absolute; left: 55%; top: 60%; z-index: 5; color: azure; } .img { position: absolute; height: 60%; }
HTML
<main> <div class="scrollable"> <div class="container"> <div class="image-container"> <h1>TEMPLE</h1> <img src="https://picsum.photos/id/1/300/200" alt="" class="img"> </div> <div class="image-container"> <h1>STREET</h1> <img src="https://picsum.photos/id/2/300/200" alt="" class="img"> </div> <div class="image-container"> <h1>RESTAURANT</h1> <img src="https://picsum.photos/id/3/300/200" alt="" class="img"> </div> <div class="image-container"> <h1>OSAKA</h1> <img src="https://picsum.photos/id/4/300/200" alt="" class="img"> </div> <div class="image-container"> <h1>DAY TIME</h1> <img src="https://picsum.photos/id/5/300/200" alt="" class="img"> </div> <div class="image-container"> <h1>CANAL</h1> <img src="https://picsum.photos/id/6/300/200" alt="" class="img"> </div> </div> </div> </main> <script src="./js/osaka.js"></script>
内容的提问来源于stack exchange,提问作者Ivy
相关产品推荐
相关产品推荐

