有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
您可以使用媒体查询来轻松处理它。
isMobile = function(){
var isMobile = window.matchMedia("only screen and (max-width: 760px)");
return isMobile.matches ? true : false
}
其他回答
一种简单有效的内衬:
function isMobile() { return ('ontouchstart' in document.documentElement); }
然而,上述代码没有考虑到带有触摸屏的笔记本电脑的情况。因此,我提供了基于@Julian解决方案的第二个版本:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
仅使用matchMedia的IE10+解决方案:
const isMobile = () => window.matchMedia('(max-width: 700px)').matches
isMobile()返回布尔值
你需要控制大小
var is_mobile = false;
$(window).resize(function() {
if ($('#mobileNav').css('display') == 'block') {
is_mobile = true;
}
if (is_mobile == true) {
console.log('is_mobile')
document.addEventListener(
"DOMContentLoaded", () => {
new Mmenu("#mainMenu", {
"offCanvas": {
"position": "right-front"
}
});
}
);
}
}).resize();
如果使用引导,可以将此元素添加到页面并检查其可见性:
<div id="mobile-detect" class="d-sm-none d-md-block" > </div>
function is_mobile() {
if( $('#mobile-detect').css('display')=='none') {
return true;
}
return false
}
我知道这是一个关于这种检测的老问题。
我的解决方案基于滚动条宽度(是否存在)。
//此函数将检查滚动条的宽度//如果滚动条宽度为0px,则为移动设备//函数ismob(){var dv=文档.getElementById('divscr');var sp=文档.getElementById('res');如果(dv.offsetWidth-dv.clientWidth==10){sp.innerHTML=“是移动的”;//返回true;}其他{sp.innerHTML=“它不是移动的”//return false;}//}<!-- 将隐藏的div放在页面-->的开头</div><span id=“res”></span>