2010-01-09 183 views
12

我正在使用snipplr的這個腳本,我如何設置它使得容器div比newWindowHeight的高度小100px,比如-100或者什麼的。jQuery:檢測瀏覽器調整大小

<script type="text/javascript" charset="utf-8"> 
$(document).ready(function(){ 

//If the User resizes the window, adjust the #container height 
$(window).bind("resize", resizeWindow); 
function resizeWindow(e) { 
    var newWindowHeight = $(window).height(); 
    $("#container").css("max-height", newWindowHeight); 
} 

});   
</script> 

回答

30

您發現的腳本過分複雜的問題。以下爲我工作:

$(function(){ 

    // Cache reference to our container 
    var $container = $("#container"); 

    // A function for updating max-height 
    function updateMaxHeight() { 
     $container.css("max-height", $(this).height() - 100); 
    } 

    // Call updateMaxHeight when browser resize event fires 
    $(window).on("resize", updateMaxHeight); 

}); 

一個警告是resize事件調用瀏覽器時調用了很多;它不僅在瀏覽器調整大小後才調用。因此,你可以讓回調函數被調用數百次 - 這通常是一個壞主意。

解決方案是遏制或消除事件。節流意味着您不會讓回調在一段時間內被觸發超過x次(可能是每秒5次)。去抖動意味着您在最後一次調整大小事件經過了一定時間後觸發回調(等待調整大小事件後500毫秒)。

jQuery目前不支持油門或反彈選項,雖然有插件。 Other popular libraries you may have used do have these features,如下劃線:

$(function(){ 

    // Cache reference to our container 
    var $container = $("#container"); 

    // A function for updating max-height 
    function updateMaxHeight() { 
     $container.css("max-height", $(this).height() - 100); 
    } 

    // Version of updateMaxHeight that will run no more than once every 200ms 
    var updateMaxHeightThrottled = _.throttle(updateMaxHeight, 200); 

    // Call updateMaxHeightThrottled when browser resize event fires 
    $(window).on("resize", updateMaxHeightThrottled); 

}); 
0

我剛纔看到名爲「在onResize」的HTML事件屬於特別標記 將有更多的表現那麼Java檢測這種用法,我認爲。

<body onresize="functionhere()"> 

我希望這將有助於你們..