javascript - 如何在有限的时间内在 vanilla JS 中添加一个类?
问题描述
我想在 JS 中禁用滚动几秒钟。现在我有这个,但每次我滚动页面时它会阻塞一秒钟然后阻塞停止,然后我滚动它会再次阻塞,等等。
我希望在滚动页面后只停止一次阻塞。这是我的代码:
HTML
<div class="cover" id="cover">
...
</div>
<div class="container" id="container">
...
</div>
JS
var scrollPosition = window.scrollY;
var cover = document.getElementsByClassName("cover")[0];
window.addEventListener("scroll", function () {
scrollPosition = window.scrollY;
if (scrollPosition >= 1) {
cover.classList.add("cover-close");
document.body.classList.add("stop-scrolling");
setTimeout(function() {
document.body.classList.remove("stop-scrolling");
}, 1000);
} else {
cover.classList.remove("cover-close");
}
});
萨斯
.stop-scrolling
height: 100%
overflow: hidden
有人有解决方案吗?谢谢!
解决方案
我会添加一个变量来检查您之前是否滚动和阻止过。
var scrollPosition = window.scrollY;
var cover = document.getElementsByClassName("cover")[0];
var hasBlocked = false;
window.addEventListener("scroll", function () {
scrollPosition = window.scrollY;
if (scrollPosition >= 1) {
cover.classList.add("cover-close");
if (!hasBlocked) {
hasBlocked = true;
document.body.classList.add("stop-scrolling");
setTimeout(function() {
document.body.classList.remove("stop-scrolling");
}, 1000);
}
} else {
cover.classList.remove("cover-close");
}
});
推荐阅读
- laravel - 如何在 Vue FullCalendar 上的事件中添加图像?imageurl 返回未定义
- azure - 如何针对存储帐户运行多个子 Runbook
- c# - AmazonS3Client 找不到路径的一部分
- c# - 从 DataRow 第 N 列分配 DataGridRow.Header 值
- python - FreqDist 用于最常见的单词或短语
- angular - 如何将html值传递给javascript或通过环回使用两种方式绑定?
- java - 如何正确创建一组预定义的 JObject?
- r - 如何在 ggplot2 中按 geom / layer 进行分面?
- kubernetes - 构建/编译 Kubernetes 仅用于签名验证而不是签名
- android - Android Picasso Recyclerview 图片下载慢