jQuery: detecting a browser resize

前端 未结 2 1614
醉话见心
醉话见心 2021-02-04 08:27

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.



        
相关标签:
2条回答
  • 2021-02-04 08:45

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

    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.

    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 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);
    
    });
    
    0 讨论(0)
  • 2021-02-04 08:59

    I have just seen the HTML event called "onResize" which belongs to especially tag It will have more performance then java detection with this usage I think.

    <body onresize="functionhere()">
    

    I hope it will help you guys..

    0 讨论(0)
提交回复
热议问题