JavaScript window resize event

前端 未结 13 777
余生分开走
余生分开走 2020-11-22 00:58

How can I hook into a browser window resize event?

There\'s a jQuery way of listening for resize events but I would prefer not to bring it into my project for just t

13条回答
  •  灰色年华
    2020-11-22 01:19

    I do believe that the correct answer has already been provided by @Alex V, yet the answer does require some modernization as it is over five years old now.

    There are two main issues:

    1. Never use object as a parameter name. It is a reservered word. With this being said, @Alex V's provided function will not work in strict mode.

    2. The addEvent function provided by @Alex V does not return the event object if the addEventListener method is used. Another parameter should be added to the addEvent function to allow for this.

    NOTE: The new parameter to addEvent has been made optional so that migrating to this new function version will not break any previous calls to this function. All legacy uses will be supported.

    Here is the updated addEvent function with these changes:

    /*
        function: addEvent
    
        @param: obj         (Object)(Required)
    
            -   The object which you wish
                to attach your event to.
    
        @param: type        (String)(Required)
    
            -   The type of event you
                wish to establish.
    
        @param: callback    (Function)(Required)
    
            -   The method you wish
                to be called by your
                event listener.
    
        @param: eventReturn (Boolean)(Optional)
    
            -   Whether you want the
                event object returned
                to your callback method.
    */
    var addEvent = function(obj, type, callback, eventReturn)
    {
        if(obj == null || typeof obj === 'undefined')
            return;
    
        if(obj.addEventListener)
            obj.addEventListener(type, callback, eventReturn ? true : false);
        else if(obj.attachEvent)
            obj.attachEvent("on" + type, callback);
        else
            obj["on" + type] = callback;
    };
    

    An example call to the new addEvent function:

    var watch = function(evt)
    {
        /*
            Older browser versions may return evt.srcElement
            Newer browser versions should return evt.currentTarget
        */
        var dimensions = {
            height: (evt.srcElement || evt.currentTarget).innerHeight,
            width: (evt.srcElement || evt.currentTarget).innerWidth
        };
    };
    
    addEvent(window, 'resize', watch, true);
    

提交回复
热议问题