winney

It is never too old to learn.

0%
winney

当页面内容过长,出现滚动条的情况下,显示弹窗时,禁止弹窗底下的页面内容可滑动;隐藏弹窗时,页面恢复可滑动

显示弹窗.png (377×538) (raw.githubusercontent.com)

控制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 });

本地预览:

1
hexo s

当默认端口4000被占用时:

1
FATAL Port 4000 has been used. Try other port instead.

解决默认端口4000被占用:

  1. 直接在终端命令行中指定端口

    1
    hexo server -p 4002
  2. 修改项目运行所在端口号

    修改package.json文件里的server,修改前: "server": "hexo server" 修改后: "server": "hexo server -p 4001" 注意:这时候你需.

    1
    npm run server