当页面内容过长,出现滚动条的情况下,显示弹窗时,禁止弹窗底下的页面内容可滑动;隐藏弹窗时,页面恢复可滑动
控制body样式来实现
显示弹窗:
1 2 3 4 5 6 7 8
| function openModal() { const modalContainer = document.getElementById('modalContainer'); // 弹窗内容 const mask = document.getElementById('mask'); // 蒙层
modalContainer.style.display = 'block'; mask.style.display = 'block'; document.body.style.overflow = 'hidden'; // 禁止滚动 }
|
隐藏弹窗:
1 2 3 4 5 6 7 8
| function closeModal() { const modalContainer = document.getElementById('modalContainer'); // 弹窗内容 const mask = document.getElementById('mask'); // 蒙层
modalContainer.style.display = 'none'; mask.style.display = 'none'; document.body.style.overflow = ''; // 允许滚动 }
|
event.preventDefault()
方法(取消事件的默认行为)
显示弹窗:
1 2 3 4 5 6 7 8 9
| let isModalOpen = false; function openModal() { const modalContainer = document.getElementById('modalContainer'); // 弹窗内容 const mask = document.getElementById('mask'); // 蒙层
modalContainer.style.display = 'block'; mask.style.display = 'block'; isModalOpen = true; }
|
隐藏弹窗:
1 2 3 4 5 6 7 8
| function closeModal() { const modalContainer = document.getElementById('modalContainer'); // 弹窗内容 const mask = document.getElementById('mask'); // 蒙层
modalContainer.style.display = 'none'; mask.style.display = 'none'; isModalOpen = false; }
|
添加事件监听:
1 2 3 4 5 6 7
| function preventScrolling(event) { if (isModalOpen) { event.preventDefault(); } } window.addEventListener('scroll', preventScrolling); window.addEventListener('touchmove', preventScrolling);
|
会报错:[Intervention] Unable to preventDefault inside passive event listener due to target being treated as passive. See <URL>
解决报错:
事件监听,加上{ passive: false }
参数
1 2
| window.addEventListener('scroll', preventScrolling, { passive: false }); window.addEventListener('touchmove', preventScrolling, { passive: false });
|