简体   繁体   English

检查浏览器宽度并仅触发一次事件

[英]Check browser width and fire event only once

  • I want to check my browser/window width, for when it is below 669px.我想检查我的浏览器/窗口宽度,当它低于 669 像素时。
  • When it is below 669px, I want to fire a function only once .当它低于 669px 时,我只想触发一个函数一次
  • However, every time I resize my browser than further less than 669px, why function keeps on firing, with every resize.但是,每次我将浏览器的大小调整为小于 669 像素时,为什么每次调整大小时函数都会继续触发。

How do I only fire an event once, once the user hits below 669px?一旦用户点击低于 669 像素,我如何只触发一次事件?

Here's the code I'm working with:这是我正在使用的代码:

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

I think you need to create a var who is set to false if the event was start and set to true if he never been start like this:我认为你需要创建一个变量,如果事件开始,则设置为 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); } };

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

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