简体   繁体   English

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? 如何检测用户何时调整浏览器窗口大小?

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时进行somenthing。

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 n would execute that code a ridiculous number of times while you resize a window that meets those conditions. 请注意这一点,因为当宽度小于n时执行代码的if语句在调整满足这些条件的窗口时会执行该代码的次数是荒谬的。 Better to set some flags or add classes to the document, and make those part of your condition as well. 最好设置一些标志或为文档添加类,并使这些部分成为您的条件。

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 . 但是,你所问的听起来最适合用CSS Media Queries来解决。 For instance, if we wanted to change the body background color when the window is less than 900px: 例如,如果我们想在窗口小于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

jQuery: jQuery的:

$(window).resize(function() {
    //do something

    var width = $(document).width();
    if (width < 900) {
       // do something else
    }
});

You can use $(window).resize() like follows 您可以使用$(window).resize() ,如下所示

$(window).resize(function() {
     if($(this).width() < 900)
       //do whatever you want
  });

Here is the documentation for $.resize 这是$ .resize的文档

$(window).resize(function() {
  $('body').prepend('<div>' + $(window).width() + '</div>');
  // Do stuff
});

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)');
 });​

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM