2015-03-31 72 views
0

我有這個功能,當你點擊html時,它會檢查一些元素的寬度並將它與窗口寬度進行比較。我無法讓它與調整大小功能一起工作。我想我說錯了。調整大小和調用函數

$(document).ready(function() { 
 

 
    $(window).resize(function() { 
 
    var conditionWidth = checkWidth() 
 
    }); 
 

 
    function checkWidth() { 
 
    var elementWidth = 1; 
 
    $("div>div").each(function() { 
 
     if ($(this).width() > $("html").width()/2) { 
 
     elementWidth = 2; 
 
     } 
 
    }); 
 
    return elementWidth; 
 
    } 
 

 
    var conditionWidth = checkWidth() 
 

 
    $("body").off("click").click(function() { 
 
    alert(conditionWidth); 
 
    }); 
 
})
div div { 
 
    position: relative; 
 
    height: 100px; 
 
    width: 100px; 
 
    margin-top: 20px; 
 
} 
 
.rectangle1 { 
 
    background-color: black; 
 
    width: 100px; 
 
} 
 
.rectangle2 { 
 
    background-color: red; 
 
    width: 200px; 
 
} 
 
.rectangle3 { 
 
    background-color: black; 
 
    width: 300px; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 

 
<div> 
 
    <div class="rectangle1"></div> 
 
    <div class="rectangle2"></div> 
 
    <div class="rectangle3"></div> 
 
</div>

回答

1

由於您使用var宣佈在調整大小處理程序變量的變量是局部的調整大小處理方法和關閉範圍的值(DOM就緒處理)不更新。

$(document).ready(function() { 

    var conditionWidth = checkWidth() 

    $(window).resize(function() { 
     //when you use var it becomes a local variable 
     conditionWidth = checkWidth() 
    }); 

    function checkWidth() { 
     var elementWidth = 1; 
     $("div>div").each(function() { 
      if ($(this).width() > $("html").width()/2) { 
       elementWidth = 2; 
      } 
     }); 
     return elementWidth; 
    } 

    $("body").off("click").click(function() { 
     alert(conditionWidth); 
    }); 
})