jQuery:检测浏览器调整大小 [英] jQuery: detecting a browser resize

查看:143
本文介绍了jQuery:检测浏览器调整大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用snipplr中的此脚本,如何设置它,以便容器div比newWindowHeight高度小100px,例如-100之类的东西.

I am using this script from snipplr, How would I set it so the container div is 100px less than the newWindowHeight height, like -100 or something.

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

推荐答案

您发现的脚本使问题变得更加复杂.以下对我有用:

The script you found over-complicated the issue. The following worked for me:

$(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事件被调用很多;调整浏览器大小后,不仅会调用它.结果,您可能使回调函数被调用了数百次-这通常是个坏主意.

One warning is that the resize event gets called a lot when resizing the browser; it's not just called after the browser has been resized. As a result, you could have the callback function being called hundreds of times - this is generally a bad idea.

解决方案是限制或消除该事件的反弹.节流意味着您不会在一段时间内(可能是每秒5次)触发多次回调.反跳意味着您从上一次调整大小事件开始经过了一定的时间间隔后才触发回调(等待直到调整大小事件发生后500毫秒).

The solution would be to throttle, or debounce the event. Throttling means you won't let the callback be fired more than x times in a span of time (maybe 5 times a second). Debouncing means you fire the callback after a certain span of time has passed from the last resize event (wait until 500 milliseconds after a resize event).

尽管有插件,但jQuery目前不支持节流或反跳选项. 您可能使用过的其他流行的库确实具有这些功能,例如下划线:

jQuery doesn't presently support a throttle or debounce option, though there are plugins. Other popular libraries you may have used do have these features, such as 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);

});

这篇关于jQuery:检测浏览器调整大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆