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

时间:2013-04-07 00:51:33

标签: javascript jquery responsive

如果页面宽度小于1200px并且响应速度如何,我如何制作提醒弹出窗口?

谢谢!

2 个答案:

答案 0 :(得分:3)

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

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

如果你只是想要原生的jQuery:

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

为了完整性,继承了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;
  }
}

答案 1 :(得分:0)

对于未来的Google员工,2019年的解决方案是使用JavaScript的window​.match​Media()。在所有主流浏览器和IE 10及更高版本中均为supported

您可以像这样使用它:

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

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

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

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

查看有关match​Media的Mozilla文档,以了解更多信息,以及有关Testing media queries programmatically的更多信息。

相关问题