2016-11-07 3 views
0

ウィンドウが一定の幅(1023px)に達したら2 divの内容を入れ替えたいのですが、ウィンドウのサイズを変更するたびにスワップコードを実行し続けることは望ましくありません特定の条件が満たされた後でコードを1回だけ実行する方法はありますか?

$(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

(あなたが機能のサイズを変更の上)と、それに対してチェックあなたは、単純な変数を設定することができます:既にその幅(1023px)に達しました。

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

 
    }; 
 
})();

関連する問題