2010-01-09 47 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()"> 

我希望这将有助于你们..