JavaScript window resize event

2018-12-31 04:09发布

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 this one requirement.

12条回答
听够珍惜
2楼-- · 2018-12-31 04:57

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);
查看更多
伤终究还是伤i
3楼-- · 2018-12-31 04:57

The following blog post may be useful to you: Fixing the window resize event in IE

It provides this code:

Sys.Application.add_load(function(sender, args) {
    $addHandler(window, 'resize', window_resize);
});

var resizeTimeoutId;

function window_resize(e) {
     window.clearTimeout(resizeTimeoutId);
     resizeTimeoutId = window.setTimeout('doResizeCode();', 10);
}
查看更多
伤终究还是伤i
4楼-- · 2018-12-31 05:04

jQuery is just wrapping the standard resize DOM event, eg.

window.onresize = function(event) {
    ...
};

jQuery may do some work to ensure that the resize event gets fired consistently in all browsers, but I'm not sure if any of the browsers differ, but I'd encourage you to test in Firefox, Safari, and IE.

查看更多
冷夜・残月
5楼-- · 2018-12-31 05:05

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');
});
查看更多
爱死公子算了
6楼-- · 2018-12-31 05:05

The already mentioned solutions above will work if all you want to do is resize the window and window only. However, if you want to have the resize propagated to child elements, you will need to propagate the event yourself. Here's some example code to do it:

window.addEventListener("resize", function () {
  var recResizeElement = function (root) {
    Array.prototype.forEach.call(root.childNodes, function (el) {

      var resizeEvent = document.createEvent("HTMLEvents");
      resizeEvent.initEvent("resize", false, true);
      var propagate = el.dispatchEvent(resizeEvent);

      if (propagate)
        recResizeElement(el);
    });
  };
  recResizeElement(document.body);
});

Note that a child element can call

 event.preventDefault();

on the event object that is passed in as the first Arg of the resize event. For example:

var child1 = document.getElementById("child1");
child1.addEventListener("resize", function (event) {
  ...
  event.preventDefault();
});
查看更多
谁念西风独自凉
7楼-- · 2018-12-31 05:10
<script language="javascript">
    window.onresize = function() {
    document.getElementById('ctl00_ContentPlaceHolder1_Accordion1').style.height = '100%';
} 

</script>
查看更多
登录 后发表回答