jQuery: 检测浏览器调整大小

13

我正在使用来自snipplr的这个脚本,如何设置容器div比newWindowHeight高度少100像素,例如-100或其他值。

<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>
2个回答

31

你找到的脚本过于复杂。以下方法对我有效:

$(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次)。防抖动意味着你要在经过上一个resize事件之后等待一定时间间隔后才触发回调(例如等待500毫秒)。

jQuery目前不支持节流或防抖选项,不过有插件可以实现。 你可能使用过其他流行库,并具备这些特性,比如underscore:

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

我刚刚看到了HTML事件,名为“onResize”,它属于特定的标签。 我认为使用它比Java检测会有更好的性能。

<body onresize="functionhere()">

希望这能对你们有所帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接