jQuery resize function doesn't work on page load

后端 未结 5 1666
情话喂你
情话喂你 2020-11-28 14:05

How do I get this function to not only run on window resize but also on initial page load?

$(window).resize(function() {
...  
});
5条回答
  •  渐次进展
    2020-11-28 14:38

    This behavior is by design.

    You should put your code into a named function, then call the function.

    For example:

    function onResize() { ... }
    
    $(onResize);
    $(window).resize(onresize);
    

    Alternatively, you can make a plugin to automatically bind and execute a handler:

    $.fn.bindAndExec = function(eventNames, handler) {
        this.bind(eventNames, handler).each(handler);
    };
    
    $(window).bindAndExec('resize', function() { ... });
    

    Note that it won't work correctly if the handler uses the event object, and that it doesn't cover every overload of the bind method.

提交回复
热议问题