简体   繁体   English

如何在香草JS中限时添加class?

[英]How to add a class in vanilla JS for a limited time?

I'd like to disable scrolling in JS for a few seconds.我想在 JS 中禁用滚动几秒钟。 Right now I have this, but everytime I scroll the page it blocks for one second then the blocking stops, then I scroll and it blocks again, etc.现在我有这个,但每次我滚动页面时它会阻塞一秒钟然后阻塞停止,然后我滚动它会再次阻塞,等等。

I'd like to have the blocking stopped only once after I scroll the page.我希望在滚动页面后只停止一次阻塞。 This is my code:这是我的代码:

HTML HTML

<div class="cover" id="cover">
    ...
</div>

<div class="container" id="container">
    ...
</div>

JS 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");
    }
});

Sass Sass

.stop-scrolling 
    height: 100%
    overflow: hidden

Someone has a solution?有人有解决方案吗? Thanks!谢谢!

I'd add a variable that checks if you've scrolled and blocked before.我会添加一个变量来检查您之前是否滚动和阻止过。

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");
    }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM