调整大小功能多次触发

时间:2019-05-27 20:09:34

标签: javascript

我使用resize()方法运行函数,该函数将返回   各种视口尺寸,例如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;
  }
 }

预期结果:调整大小功能在特定视口执行 实际结果:多次执行大小调整,从而产生DOM故障。

1 个答案:

答案 0 :(得分:1)

您需要一个变量来跟踪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();
           }
         })  
     };