automatically detect web browser window width change?

不问归期 提交于 2019-12-02 18:59:41

Try the resize event

$(window).resize(function() {
  console.log('window was resized');
});

The JavaScript event is named window.onresize.

The JQuery binding is named .resize()

Writing this down cause somehow none of these answers give the modern best-practices way of doing this:

window.addEventListener("resize", function(event) {
    console.log(document.body.clientWidth + ' wide by ' + document.body.clientHeight+' high');
})

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.

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.

I use media="only screen and (min-width: 750px)" href="... css file for wide windows" media="only screen and (max-width: 751px)" href="...css file for mobiles"

When I move the right windows border left and right to increase and decrease my window size, my web browser will automatically switch from the wide window to the mobile. I do not have to include any Javascript code to detect window width. This works for Chrome, Firefox and Internet Explorer on both Windows and Macintosh computers.

Luke Dohner

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.

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);
       }
    });
})();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!