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

Har*_*rry 4 javascript jquery responsive

如果页面宽度小于1200px,我如何制作警报弹出窗口,并做出响应?

谢谢!

Bra*_*tie 7

您可以使用类似断点模块的东西。然后设置一个断点以在 1200px 处触发并显示一个对话框,然后添加一个更改布局的 css 类,或者使用直接的 javascript 进行更改。

breakpoints(1200, function(oldPoint, newPoint) {
  alert('The screen width just changed');
});
Run Code Online (Sandbox Code Playgroud)

如果你只是想要原生 jQuery:

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

为了完整起见,这里是 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;
  }
}
Run Code Online (Sandbox Code Playgroud)


Stu*_*who 6

对于未来的 Google 员工,2019 年的解决方案是使用 JavaScript 的window?.match?Media(). 所有主要浏览器和 IE 10都支持它。

你可以这样使用它:

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

要使其具有响应性,您只需要将其包装在一个resize函数中:

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

这可以说是检查屏幕尺寸的最简单方法,而且不会使代码膨胀。

查看有关match?Media的 Mozilla 文档以了解更多信息,查看有关以编程方式测试媒体查询的更多信息。