DOM event fired by window resize

后端 未结 5 2129
攒了一身酷
攒了一身酷 2021-02-10 04:34

I have a page that has a fairly complicated layout. When the page is initially opened there\'s a problem with the aligment of some of the elements. However, this problem can be

相关标签:
5条回答
  • 2021-02-10 05:08

    I tried this in Chrome, Firefox and IE11, and it works:

    var evt = document.createEvent('UIEvents');
    evt.initUIEvent('resize', true, false, window, 0);
    window.dispatchEvent(evt);
    
    0 讨论(0)
  • 2021-02-10 05:14

    There's an window.onresize event that fires when the window is resized. You can force a resize by changing the window.width or height by a pixel and then setting it back on a small timer.

    With jQuery you can do something like this:

    $(function() { 
       $(window).width($(window).width() + 1);
      // delay so DOM can update and not batch UI updates
      setTimeout(function() { $(window).width($(window).width() -1); },3);
    });
    

    FWIW, I've seen this myself before, but I agree with @bouke that you should defintitely try to identify what's causing the broken layout. I find it usually has to do with floated content or overflow of text containers that causes these sorts of problems.

    0 讨论(0)
  • 2021-02-10 05:19

    I think you should investigate why the page does not render correctly in the first place. Relying on a re-render after resize sounds hackish to me.

    Although manually firing a resize event might not give the correct results, you can also try to hide/show an event triggering a re-render event. This might result in screen flickering, so it is not the optimal solution.

    0 讨论(0)
  • 2021-02-10 05:21

    Can also be done with CustomEvent:

    var ev = new CustomEvent('resize'); //instantiate the resize event
    ev.initEvent('resize');
    
    window.dispatchEvent(ev); // fire 'resize' event!
    
    0 讨论(0)
  • 2021-02-10 05:27

    For IE compatibility

    function fireResize(){
        if (document.createEvent) { // W3C
            var ev = document.createEvent('Event');
            ev.initEvent('resize', true, true);
            window.dispatchEvent(ev);
        }
        else { // IE
            element=document.documentElement;
            var event=document.createEventObject();
            element.fireEvent("onresize",event);
        }
    };
    fireResize();
    
    0 讨论(0)
提交回复
热议问题