仅检查一次浏览器宽度和fire事件

r6hnlfcb  于 2021-09-29  发布在  Java
关注(0)|答案(1)|浏览(210)

我想检查我的浏览器/窗口宽度是否低于669px。
当它低于669px时,我只想启动一次函数。
然而,每次我将浏览器的大小调整到669px以下时,为什么每次调整大小时都会继续启动该功能。
当用户达到669px以下时,我如何只触发一次事件?
以下是我正在使用的代码:

const checkWindowWdith = () => {
    console.log(document.documentElement.clientWidth);
    if (document.documentElement.clientWidth < 669) {
        //DO SOMETHING HERE
    };
};

//HERE I AM WAIT FOR THE USER TO FINISH RESIZING
var doit;
window.onresize = function(){
    clearTimeout(doit);
    doit = setTimeout(checkWindowWdith, 100);
};
mefy6pfw

mefy6pfw1#

我认为您需要创建一个var,如果事件是启动的,则将其设置为false;如果他从未像这样启动,则将其设置为true:

var firstStartEvent = true

const checkWindowWdith = () => {
    console.log(document.documentElement.clientWidth);
    if (document.documentElement.clientWidth < 669) {
        firstStartEvent = false;
        //DO SOMETHING HERE
    };
};

//HERE I AM WAIT FOR THE USER TO FINISH RESIZING
var doit;
window.onresize = function(){
    clearTimeout(doit);
    if (firstStartEvent) {
      doit = setTimeout(checkWindowWdith, 100);
    }
};

相关问题