JS或jQuery或窗口调整大小或窗口宽度小于npx [英] JS or jQuery or window resize or when window width is less than npx
问题描述
如何检测用户何时调整浏览器窗口大小?
How can I detect when a user resizes the browser window?
我正在寻找一个脚本,当用户调整窗口大小或窗口宽度时会进行重新设置小于,例如,900px。
I'm looking for a script that does somenthing when user resizes the window or when the window's width is less than, for example, 900px.
推荐答案
嗯,你可以使用jQuery,但是......
您可以订阅这样的窗口调整大小事件:
Meh, You can use jQuery, but...
You can subscribe to the window resize event like this:
$(window).on("resize", function(event){
console.log( $(this).width() );
});
请注意这一点,因为if语句在宽度小于<时执行代码当您调整满足这些条件的窗口时,em> n 会执行该代码的次数非常多。最好设置一些标志或为文档添加类,并使这些条件成为你的条件。
Just be careful with this, since a if-statement that executes code when the width is less than n would execute that code a ridiculous number of times while you resize a window that meets those conditions. Better to set some flags or add classes to the document, and make those part of your condition as well.
然而,你问的问题听起来最好用 CSS媒体查询。例如,如果我们想在窗口小于900px时更改主体背景颜色:
However, what you're asking sounds like it would most appropriately be solved with CSS Media Queries. For instance, if we wanted to change the body background color when the window is less than 900px:
@media screen and (max-width: 900px) {
body {
background: #ccc;
}
}
对于旧版本的IE,甚至还有一个很棒的polyfill: https://github.com/scottjehl/Respond
There's even a great polyfill for older version of IE: https://github.com/scottjehl/Respond
这篇关于JS或jQuery或窗口调整大小或窗口宽度小于npx的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!