Javascript JS 或 jQuery 或窗口调整大小或当窗口宽度小于 npx 时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10642424/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JS or jQuery or window resize or when window width is less than npx
提问by itsme
How can I detect when a user resizes the browser window?
如何检测用户何时调整浏览器窗口大小?
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.
我正在寻找一个脚本,当用户调整窗口大小或窗口宽度小于例如 900px 时,该脚本会执行某些操作。
回答by Sampson
Meh, You can use jQuery, but...
嗯,您可以使用 jQuery,但是...
You can subscribe to the window resize event like this:
您可以像这样订阅窗口调整大小事件:
$(window).on("resize", function(event){
console.log( $(this).width() );
});
Just be careful with this, since a if-statement that executes code when the width is less than nwould 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.
请注意这一点,因为在宽度小于n时执行代码的 if 语句会在您调整满足这些条件的窗口大小时执行该代码的次数可笑。最好设置一些标志或向文档添加类,并使这些也成为您的条件的一部分。
CSS Media Queries is Where It's At!
CSS 媒体查询就在这里!
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:
但是,您所问的问题听起来最适合使用CSS Media Queries解决。例如,如果我们想在窗口小于 900px 时更改主体背景颜色:
@media screen and (max-width: 900px) {
body {
background: #ccc;
}
}
There's even a great polyfill for older version of IE: https://github.com/scottjehl/Respond
对于旧版本的 IE,甚至还有一个很棒的 polyfill:https: //github.com/scottjehl/Respond
回答by Silkster
jQuery:
jQuery:
$(window).resize(function() {
//do something
var width = $(document).width();
if (width < 900) {
// do something else
}
});
回答by Kvam
$(window).resize(function() {
$('body').prepend('<div>' + $(window).width() + '</div>');
// Do stuff
});
回答by Oscar Jara
According to what you need, this could handle when windows size is less than 900px:
根据您的需要,当窗口大小小于 900px 时,这可以处理:
$(window).on("resize", function(event){
console.log('User is using resize!');
var w = $(this).width();
if(w < 900)
console.log('Your window is ' + w + 'px (less than 900px)');
});?