1

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

目前我正在做

if ($(window).width() < 606) {
  do_things();
}

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

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

4

1 回答 1

4

As crude as your code might look to you, this is actually in a nutshell what a media query is. If you look at the source for responsive.js (JS lib that adds media query support to older browsers) it includes this function:

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;
}

While this is a more complete approach to detecting device width (and this is combined with an onResize event handler to detect things like rotation), it is fundamentally what you are doing.

于 2013-08-14T16:51:03.580 回答