简体   繁体   English

jQuery-如果屏幕小于指定的宽度(响应)

[英]jQuery - If screen is less than specified width (responsive)

How can I make an alert popup if the width of the page is less than 1200px , and made responsive? 如果页面的宽度小于1200px并作出响应,该如何弹出警报?

Thanks! 谢谢!

You can use something like the breakpoints module. 您可以使用类似断点模块的东西。 Then you setup a breakpoint to trigger at 1200px and show a dialog and either add a css class that changes the layout, or use straight javascript to make the changes. 然后,您设置一个断点以在1200px处触发并显示一个对话框,并添加一个更改布局的css类,或使用直接的javascript进行更改。

breakpoints(1200, function(oldPoint, newPoint) {
  alert('The screen width just changed');
});

if you just wanted native jQuery: 如果您只想要本机jQuery:

$(window).resize(function() {
  var width = $(window).width();
  if (width < 1200){
    alert('Your screen is too small');
  }
});

For completeness, heres the CSS media query (still doesn't take care of the alert, but can help with making the website "responsive"). 为了完整起见,这里使用CSS媒体查询(仍然不处理警报,但是可以帮助使网站“响应”)。

/* some normal style */
.myclass {
  font-size: 22pt;
}

/* alter the style when the screen's smaller */
@media screen and (max-width: 1200px) {
  .myclass {
    font-size: 18pt;
  }
}

For future Googlers, a 2019 solution is to use JavaScript's window​.match​Media() . 对于未来的Google员工来说,2019年的解决方案是使用JavaScript的window​.match​Media() It is supported in all major browsers and IE 10 onwards. 所有主要浏览器和IE 10及更高版本均支持该功能。

You can use it like this: 您可以像这样使用它:

if (window.matchMedia('(max-width: 1200px)').matches) {
    // functionality for screens smaller than 1200px
}

To make this responsive, you just need to wrap it in a resize function: 要使此响应,您只需要将其包装在一个resize函数中:

$(window).resize(function() {
    if (window.matchMedia('(max-width: 1200px)').matches) {
        // functionality for screens smaller than 1200px
    }
});

This is arguably the most easiest way to check a screen size and it doesn't bloat the code. 可以说,这是检查屏幕尺寸的最简单方法,并且不会膨胀代码。

Check the Mozilla docs about match​Media to learn more and this one for more info on Testing media queries programmatically . 检查有关Mozilla的文档匹配媒体 ,以了解更多,这一次关于更多信息编程测试媒体查询

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

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