automatically detect web browser window width change?

前端 未结 8 1418
清酒与你
清酒与你 2021-02-01 16:20

i know that you with $(window).width() can get the size of the web browser.

i want to detect when the user change the size of his web browser so i could readjust the col

相关标签:
8条回答
  • 2021-02-01 16:57

    The JavaScript event is named window.onresize.

    The JQuery binding is named .resize()

    0 讨论(0)
  • 2021-02-01 17:04

    Something to keep in mind- in IE, at least, resize events bubble, and positioned elements and the document body can fire independent resize events.

    Also, IE fires a continuous stream of 'resize' events when the window or element is resized by dragging. The other browsers wait for the mouseup to fire.

    IE is a big enough player that it is useful to have an intermediate handler that fields resize events- even if you branch only IE clients to it.

    The ie handler sets a short timeout(100-200 msec)before calling the 'real' resize handler. If the same function is called again before the timeout, it is either a bubblng event or the window is being dragged to a new size, so clear the timeout and set it again.

    0 讨论(0)
  • 2021-02-01 17:09

    Try the resize event

    $(window).resize(function() {
      console.log('window was resized');
    });
    
    0 讨论(0)
  • 2021-02-01 17:10

    In MDN they give a really good Javascript standalone code:

    window.onresize = resize;
    
    function resize()
    {
     alert("resize event detected!");
    }

    If you need just this kind of functionality I would recommend to go for it.

    0 讨论(0)
  • 2021-02-01 17:13

    You might want to use debounce : https://davidwalsh.name/javascript-debounce-function

    Otherwise the

    window.addEventListener("resize")
    

    Will fire the whole time as the window resize is in progress. Which will tax your CPU overhead.

    0 讨论(0)
  • 2021-02-01 17:15

    Here's a little piece of code I put together for the same thing.

    (function () {
        var width = window.innerWidth;
    
        window.addEventListener('resize', function () {
           if (window.innerWidth !== width) {
               window.location.reload(true);
           }
        });
    })();
    
    0 讨论(0)
提交回复
热议问题