【问题标题】:jQuery: detecting a browser resizejQuery:检测浏览器调整大小
【发布时间】:2011-01-03 03:55:55
【问题描述】:

我正在使用来自 snipplr 的这个脚本,我将如何设置它以使容器 div 比 newWindowHeight 高度小 100px,例如 -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>

【问题讨论】:

    标签: jquery resize subtraction


    【解决方案1】:

    您发现的脚本使问题过于复杂。以下对我有用:

    $(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);
    
    });
    

    一个警告是在调整浏览器大小时会多次调用调整大小事件;它不仅仅是在调整浏览器大小后调用。结果,您可能会调用数百次回调函数 - 这通常是个坏主意。

    解决方案是限制或消除事件。节流意味着您不会让回调在一段时间内被触发超过 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);
    
    });
    

    【讨论】:

      【解决方案2】:

      我刚刚看到了名为“onResize”的 HTML 事件,它属于特别标签 我认为使用这种用法它会比 java 检测具有更高的性能。

      <body onresize="functionhere()">
      

      希望对大家有帮助。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-02
        • 2017-08-08
        • 2012-09-28
        • 2012-03-18
        • 1970-01-01
        • 1970-01-01
        • 2010-10-26
        • 1970-01-01
        相关资源
        最近更新 更多