如何实现全屏首屏效果?滚动切换至新屏幕的技术问询
实现全屏首屏滚动切换效果
先纠正你原代码里的两处错误:
width: absolute是无效的CSS属性,块级元素默认占满父容器宽度,若需明确设置可写width: 100%- 首屏固定高度900px无法适配不同屏幕尺寸,改用视口单位vh,
height: 100vh能让元素刚好占满当前屏幕高度
下面提供两种可行的实现方案:
方案一:纯CSS基础全屏区块
适合只需要区块占满屏幕、自然滚动切换的基础需求:
CSS 代码
* { margin: 0; padding: 0; box-sizing: border-box; /* 避免内边距撑大元素尺寸 */ } .section { width: 100%; height: 100vh; /* 占满当前视口高度 */ } #section1 { background-image: linear-gradient(to right, green, blue); } #section2 { background-image: linear-gradient(to right, red, orange); }
HTML 代码
<div id="section1" class="section"></div> <div id="section2" class="section"></div>
方案二:JS辅助平滑滚动对齐区块
如果需要滚动时自动对齐到下一个全屏区块的效果,可添加简单JS逻辑:
CSS 代码
* { margin: 0; padding: 0; box-sizing: border-box; } html { scroll-behavior: smooth; /* 开启原生平滑滚动 */ } .section { width: 100%; height: 100vh; } #section1 { background-image: linear-gradient(to right, green, blue); } #section2 { background-image: linear-gradient(to right, red, orange); }
JS 代码
const sections = document.querySelectorAll('.section'); let currentIndex = 0; window.addEventListener('wheel', (e) => { e.preventDefault(); // 根据滚动方向切换当前区块索引 if (e.deltaY > 0 && currentIndex < sections.length - 1) { currentIndex++; } else if (e.deltaY < 0 && currentIndex > 0) { currentIndex--; } // 滚动到目标区块 sections[currentIndex].scrollIntoView({ behavior: 'smooth' }); }, { passive: false });
HTML 代码
<div id="section1" class="section"></div> <div id="section2" class="section"></div>
注意:方案二中的passive: false用于阻止默认滚动行为,确保区块对齐逻辑生效,部分浏览器可能需要额外兼容;若无需强制对齐,方案一完全能满足需求。
内容的提问来源于stack exchange,提问作者Daxton Taylor
相关产品推荐
相关产品推荐

