WordPress+Elementor页面点击按钮前禁滚动,点击后仍无法滚动问题
问题分析与修复方案
核心问题排查
你的代码存在几个关键问题,导致点击按钮后无法恢复滚动:
- 拼写错误:
document.body.style.heigth应为document.body.style.height,该错误导致body高度设置失效。 - DOM加载时机问题:脚本执行时Elementor可能还未渲染出
open-invitation按钮,导致点击事件绑定失败。 - 滚动恢复不彻底:仅设置
overflowY: unset和清空onscroll事件不够,需要重置body的height属性,且unset在部分浏览器兼容性不如auto。
修正后的代码
<script> // 等待页面DOM完全加载后执行逻辑 document.addEventListener('DOMContentLoaded', function() { // 初始禁止滚动 disableScrolling(); document.body.style.overflowY = 'hidden'; document.body.style.height = '100vh'; // 绑定按钮点击事件(先判断元素是否存在) const openBtn = document.getElementById('open-invitation'); if (openBtn) { openBtn.addEventListener('click', myFunction); } function myFunction() { playAudio(); // 保留你的音频播放逻辑 // 彻底恢复滚动状态 enableScrolling(); document.body.style.overflowY = 'auto'; document.body.style.height = 'auto'; } function disableScrolling() { const x = window.scrollX; const y = window.scrollY; window.onscroll = function() { window.scrollTo(x, y); }; } function enableScrolling() { window.onscroll = null; // 直接置空事件比赋值空函数更彻底 } }); </script>
额外注意事项
- Elementor脚本放置位置:建议将脚本放在Elementor的「页面设置」→「自定义代码」→「页脚」区域,确保元素渲染完成后再执行脚本。
- 按钮ID验证:在Elementor编辑器中确认按钮的ID确实是
open-invitation,检查是否存在拼写错误或重复ID。
内容的提问来源于stack exchange,提问作者David H
相关产品推荐
相关产品推荐

