javascript jQuery - 如果屏幕小于指定宽度(响应式)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15857669/
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
jQuery - If screen is less than specified width (responsive)
提问by Harry
How can I make an alert popup if the width of the page is less than 1200px
, and made responsive?
如果页面宽度小于1200px
,我如何制作警报弹出窗口,并做出响应?
Thanks!
谢谢!
回答by Brad Christie
You can use something like the breakpointsmodule. 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.
您可以使用类似断点模块的东西。然后设置一个断点以在 1200 像素处触发并显示一个对话框,然后添加一个更改布局的 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;
}
}
回答by Studocwho
For future Googlers, a 2019 solution is to use JavaScript's window?.match?Media()
. It is supportedin all major browsers and IE 10 onwards.
对于未来的 Google 员工,2019 年的解决方案是使用 JavaScript 的window?.match?Media()
. 所有主要浏览器和 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?Mediato learn more and this one for more info on Testing media queries programmatically.
查看有关match?Media的 Mozilla 文档以了解更多信息,查看有关以编程方式测试媒体查询的更多信息。