响应式 JavaScript:仅针对小设备宽度执行代码

Ale*_*eue 2 javascript jquery responsive-design twitter-bootstrap

我有一些简单的 JavaScript(嵌入在事件中),我只想为小型设备触发它们。电话等...

目前我正在做

if ($(window).width() < 606) {
  do_things();
}
Run Code Online (Sandbox Code Playgroud)

但这感觉很笨拙。有没有办法只对小于某个断点的设备执行此操作(除了设置较早的变量之外)?理想情况下,它可以与我的 CSS 断点一起使用。

我正在使用 Bootstrap,因此可能有一个简单的选项可以利用它。

Jas*_*ske 6

尽管您的代码可能看起来很粗糙,但这实际上是媒体查询的简而言之。如果您查看responsive.js(为旧浏览器添加媒体查询支持的JS库)的源代码,它包含以下功能:

function getDeviceWidth() {
    if (typeof (window.innerWidth) == 'number') {
        //Non-IE
        return window.innerWidth;
    } else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
        //IE 6+ in 'standards compliant mode'
        return document.documentElement.clientWidth;
    } else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
        //IE 4 compatible
        return document.body.clientWidth;
    }
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

虽然这是一种更完整的检测设备宽度的方法(并且与onResize事件处理程序相结合来检测旋转等内容),但这基本上就是您正在做的事情。