我有一些简单的 JavaScript(嵌入在一个事件中),我只想为小型设备触发。电话等...
目前我在做
if ($(window).width() < 606) {
do_things();
}
但这感觉很笨拙。有没有办法只对小于某个断点的设备执行此操作(除了设置较早的变量之外)?理想情况下,可以与我的 CSS 断点配合使用。
我正在使用 Bootstrap,因此可能有一个简单的选项可以利用它。
最佳答案
尽管您的代码在您看来可能很粗糙,但实际上这就是媒体查询的简而言之。如果您查看 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;
}
虽然这是一种更完整的检测设备宽度的方法(并且它与 onResize
事件处理程序相结合以检测诸如旋转之类的事情),但它基本上就是您正在做的事情。
关于javascript - 响应式 JavaScript : execute code only for small device width,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18237513/