如何实现WordPress网站每次滚动100%视口高度的分段滚动
实现WordPress网站类似Reels/TikTok的分段滚动效果
下面提供几种可行的实现方案,涵盖代码自定义和插件辅助两种路径,你可以根据自己的技术能力选择:
方案一:纯JS+CSS实现无锚点分段滚动
先通过CSS让每个内容区块占满整个视口,再用JS监听滚轮事件,直接切换到对应区块。
步骤1:添加CSS样式
在WordPress后台「外观-自定义-额外CSS」中添加以下代码:
/* 让目标区块占满视口 */ .scroll-section { height: 100vh; width: 100%; overflow: hidden; display: flex; align-items: center; justify-content: center; box-sizing: border-box; padding: 20px; margin: 0; }
步骤2:添加JS逻辑
在主题的footer.php文件末尾(或通过自定义JS插件)添加以下代码:
let currentSection = 0; const sections = document.querySelectorAll('.scroll-section'); const totalSections = sections.length; // 监听滚轮滚动 window.addEventListener('wheel', (e) => { e.preventDefault(); // 禁用默认滚动 // 判断滚动方向:向下滚为1,向上滚为-1 const scrollDir = e.deltaY > 0 ? 1 : -1; const nextSectionIdx = currentSection + scrollDir; // 边界校验,防止超出区块范围 if (nextSectionIdx >= 0 && nextSectionIdx < totalSections) { currentSection = nextSectionIdx; // 滚动到目标区块,behavior可选'smooth'平滑或'instant'直接跳转 sections[currentSection].scrollIntoView({ behavior: 'smooth', block: 'start' }); } }, { passive: false });
步骤3:标记目标区块
在WordPress编辑器中,给需要参与分段滚动的内容区块添加自定义类scroll-section即可(比如区块设置里的「高级-额外CSS类」)。
方案二:锚点+JS控制滚动步长(符合你的补充思路)
通过给区块设置锚点ID,结合JS实现滚动时按锚点跳转,同时支持菜单锚点联动。
步骤1:设置锚点ID
在编辑器中给每个目标区块设置唯一ID(比如区块设置的「高级-HTML锚点」),例如:
- 第一个区块ID:
section-1 - 第二个区块ID:
section-2 - 以此类推
步骤2:CSS样式(同方案一)
同样添加让区块占满视口的CSS:
.scroll-section { height: 100vh; width: 100%; overflow: hidden; display: flex; align-items: center; justify-content: center; box-sizing: border-box; }
步骤3:JS逻辑控制锚点跳转
添加以下JS代码:
// 按顺序列出所有锚点ID const sectionIds = ['section-1', 'section-2', 'section-3']; let currentIdx = 0; // 滚轮事件监听 window.addEventListener('wheel', (e) => { e.preventDefault(); const scrollDir = e.deltaY > 0 ? 1 : -1; const nextIdx = currentIdx + scrollDir; if (nextIdx >= 0 && nextIdx < sectionIds.length) { currentIdx = nextIdx; const targetEl = document.getElementById(sectionIds[currentIdx]); targetEl.scrollIntoView({ behavior: 'smooth' }); } }, { passive: false }); // 适配移动端触摸滑动 let touchStartY = 0; window.addEventListener('touchstart', (e) => { touchStartY = e.changedTouches[0].screenY; }); window.addEventListener('touchend', (e) => { const touchEndY = e.changedTouches[0].screenY; const swipeDir = touchEndY < touchStartY ? 1 : -1; // 上滑=下一个区块,下滑=上一个区块 const nextIdx = currentIdx + swipeDir; if (nextIdx >= 0 && nextIdx < sectionIds.length) { currentIdx = nextIdx; document.getElementById(sectionIds[currentIdx]).scrollIntoView({ behavior: 'smooth' }); } });
额外:菜单锚点联动
如果需要顶部菜单点击也能跳转到对应区块,直接在「外观-菜单」中添加自定义链接,URL填写#section-1这类锚点地址即可。
方案三:插件快速实现(无需写代码)
如果不想手动写代码,推荐两款WordPress插件:
- FullPage.js for WordPress:基于知名的FullPage.js库,一键设置全屏分段滚动,支持自定义过渡动画、导航点、移动端适配等功能。
- Page Scroll to ID:专注锚点滚动控制,可设置滚动步长、动画速度,支持自动检测锚点,配合区块ID即可实现分段跳转。
安装插件后,按照插件向导提示给目标区块添加对应类或锚点ID,即可快速启用分段滚动效果。
注意事项
- 部分主题自带平滑滚动功能,可能会和自定义JS冲突,建议先在主题设置中禁用自带的平滑滚动。
- 测试时要覆盖桌面端滚轮和移动端触摸滑动两种场景,确保切换流畅无卡顿。
- 如果区块内容高度超过视口,可调整CSS的
height为min-height: 100vh,避免内容被截断。
内容的提问来源于stack exchange,提问作者Benb1
相关产品推荐
相关产品推荐

