簡體   English   中英

調整大小功能多次觸發

[英]resize function firing multiple times

我使用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故障。

您需要一個變量來跟蹤DOM的當前狀態。

讓我們創建一個名為currentViewPort的變量,其值可以為“ desktop”,“ tablet”或“ mobile”。

當窗口調整大小時,我們將切換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();
           }
         })  
     };

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM