2016-11-07 124 views
0

我想要發生的事情是在窗口達到一定寬度(1023px)後交換2個div的內容,但我不希望它在每次調整窗口大小後都繼續運行交換代碼已經達成的寬度(1023px):如何在滿足特定條件後僅執行一次代碼?

$(window).resize(function() { 

    if($(window).width() <= 1023) {  

    var $left_col = $('.about-left-col').html(); 
    var $right_col = $('.about-right-col').html(); 

    $('.about-right-col').html($left_col); 
    $('.about-left-col').html($right_col); 

    } 

}); 

回答

0

使用==

$(window).resize(function() { 

    if($(window).width() == 1023) {  

    var $left_col = $('.about-left-col').html(); 
    var $right_col = $('.about-right-col').html(); 

    $('.about-right-col').html($left_col); 
    $('.about-left-col').html($right_col); 

    } 

}); 
0

你可以設置一個簡單的變量(上面你調整功能)和對證。

var wasResized = false; 

將其設置爲true時調整大小,並添加一個檢查條件,如果它是真/假。

0

使用全局變量來存儲狀態

var notChanged = true; 

$(window).resize(function() { 

    if($(window).width() <= 1023) {  
    if(notChanged) {//test if its not changed 
    var $left_col = $('.about-left-col').html(); 
    var $right_col = $('.about-right-col').html(); 

    $('.about-right-col').html($left_col); 
    $('.about-left-col').html($right_col); 
    notChanged = false;//set it to false so the code doesn't trigger anymore 
    } 
    } 

}); 
0

你可以嘗試這樣的,

$(window).resize(function() { 

     if($(window).width() <= 1023) {  

     var $left_col = $('.about-left-col').html(); 
     var $right_col = $('.about-right-col').html(); 

     if($('.about-right-col').html() != $left_col){ 
      $('.about-right-col').html($left_col); 
      $('.about-left-col').html($right_col); 
     }else{ 
      return false; 
     } 
     } 

}); 
0

你可以做這樣的事情,有使用閉包的功能執行的計數器並繼續如你所需。

$(window).resize(reposition); 
 

 
function reposition = ({ 
 
    var count = 0; 
 

 
    return function() { 
 
    if (count !== 0) { 
 
     return; 
 
    } 
 
    if ($(window).width() <= 1023) { 
 
     var $left_col = $('.about-left-col').html(); 
 
     var $right_col = $('.about-right-col').html(); 
 

 
     $('.about-right-col').html($left_col); 
 
     $('.about-left-col').html($right_col); 
 
     count++; 
 
    } 
 

 
    }; 
 
})();

相關問題