JavaScript window resize event

前端 未结 13 784
余生分开走
余生分开走 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:23

    Never override the window.onresize function.

    Instead, create a function to add an Event Listener to the object or element. This checks and incase the listeners don't work, then it overrides the object's function as a last resort. This is the preferred method used in libraries such as jQuery.

    object: the element or window object
    type: resize, scroll (event type)
    callback: the function reference

    var addEvent = function(object, type, callback) {
        if (object == null || typeof(object) == 'undefined') return;
        if (object.addEventListener) {
            object.addEventListener(type, callback, false);
        } else if (object.attachEvent) {
            object.attachEvent("on" + type, callback);
        } else {
            object["on"+type] = callback;
        }
    };
    

    Then use is like this:

    addEvent(window, "resize", function_reference);
    

    or with an anonymous function:

    addEvent(window, "resize", function(event) {
      console.log('resized');
    });
    

提交回复
热议问题