javascript - 调整大小函数多次触发

标签 javascript

我使用 resize() 方法来运行一个函数,该函数将返回 不同的视口(viewport)大小,如 992,768 等。问题是 每次执行函数都会导致 DOM 出现故障。例子 在codepen https://codepen.io/paul-solomon/pen/WBEgQe

//javascript

$(window).resize(function(){
nh_masonry.data.loadorder();
});


//css

.masonry_grid_quarter__container{
 margin-bottom: 8px;
 column-count:3;
 column-gap:8px;
}

@media screen and (max-width:992px){
.masonry_grid_quarter__container{
 column-count:2;
 }
}

@media screen and (max-width:768px){
 .masonry_grid_quarter__container{
  column-count:2;
  }
}

@media screen and (max-width:580px){
 .masonry_grid_quarter__container{
  column-count:1;
  }
 }

预期结果:调整大小函数在特定视口(viewport)执行 实际结果:多次执行调整大小,造成 DOM 故障。

最佳答案

您需要一个变量来跟踪 DOM 的当前状态。

让我们创建一个名为 currentViewPort 的变量,其值为“桌面”、“平板电脑”或“移动设备”。

当窗口大小调整时,我们将切换currentViewPort的值。如果 currentViewPort 已经与我们的屏幕布局匹配,那么我们将不会再次调用该函数。仅当我们输入不同的布局时才会调用它。

这是在行动:https://codepen.io/anon/pen/GaGboG?editors=1111

   var App = (function ($) {

   var nh_masonry = {};
   var currentViewPort = ""
   //sets initial reorder variable
   nh_masonry.vars = { reorder : false} 

   nh_masonry.onload = function () {
            // when the document is loaded sets the reorder variable to true
            // and also loads the order object method 
            nh_masonry.vars.reorder = !nh_masonry.vars.reorder;
            nh_masonry.data.loadorder();

     $(window).resize(function(){
           // re-set layout after resize
           if($( window ).width() <= 992 && $( window ).width() > 768 && currentViewPort !== "desktop"){

             currentViewPort = "desktop"
             console.log("desktop");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();

           } else if ($( window ).width() == 768 && currentViewPort !== "tablet"){

             currentViewPort = "tablet"
             console.log("tablet");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();

           } else if ($( window ).width() < 768 && $( window ).width() >= 380 && currentViewPort !== "mobile"){
            currentViewPort = "mobile"
             console.log("mobile");
              nh_masonry.data.loadorder();
              // nh_masonry.responsive.tablet();
              // nh_masonry.responsive.mobile();
           }
         })  
     };

关于javascript - 调整大小函数多次触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56331943/

相关文章:

javascript - 阻止 javascript 警告框

javascript - 旋转图像的 SVG 低性能

javascript - 如何在 Javascript 中的某个限制后打破数组

javascript - Angular 2 + Typescript显示函数内的变量

javascript - 在 Highcharts 中使两个系列指向相反的方向

javascript - JQuery 在哪里为 .fadeIn 和 .fadeOut() 调用 setInterval?

javascript - for i in bin(n)[3 :]: in Javascript? 等价于什么

javascript - 在 IE 中以编程方式隐藏弹出窗口

javascript - 查找 'unknown' 形式的所有单选按钮

javascript - 使用 Electron 从 anchor 标记保存文件