有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
我使用这个解决方案,它在所有设备上都很好:
if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {
//is_mobile
}
其他回答
屏幕可能位于分辨率较小的桌面上,也可能位于分辨率较宽的手机上,因此,结合本问题中的两个答案
const isMobile = window.matchMedia("only screen and (max-width: 760px)");
if (/Mobi|Tablet|iPad|iPhone/i.test(navigator.userAgent) || isMobile.matches) {
console.log('is_mobile')
}
你也可以像下面这样检测它
$.isIPhone = function(){
return ((navigator.platform.indexOf("iPhone") != -1) || (navigator.platform.indexOf("iPod") != -1));
};
$.isIPad = function (){
return (navigator.platform.indexOf("iPad") != -1);
};
$.isAndroidMobile = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && ua.indexOf("mobile");
};
$.isAndroidTablet = function(){
var ua = navigator.userAgent.toLowerCase();
return ua.indexOf("android") > -1 && !(ua.indexOf("mobile"));
};
你需要控制大小
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();
添加:
在某些版本的iOS 9.x中,Safari不会在navigator.userAgent中显示“iPhone”,而是在navigater.platform中显示。
var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent);
if(!isMobile){
isMobile=/iPhone|iPad|iPod/i.test(navigator.platform);
}
我知道这个问题有很多答案,但从我所看到的情况来看,没有人能以我的方式解决这个问题。
CSS使用宽度(媒体查询)来确定应用于基于宽度的web文档的样式。为什么不在JavaScript中使用宽度?
例如,在Bootstrap(Mobile First)媒体查询中,存在4个快照/断点:
超小型设备为768像素及以下。小型设备的像素范围从768到991。中等设备的范围从992到1199像素。大型设备为1200像素及以上。
我们也可以使用它来解决JavaScript问题。
首先,我们将创建一个函数,该函数获取窗口大小并返回一个值,该值允许我们查看设备正在查看我们的应用程序的大小:
var getBrowserWidth = function(){
if(window.innerWidth < 768){
// Extra Small Device
return "xs";
} else if(window.innerWidth < 991){
// Small Device
return "sm"
} else if(window.innerWidth < 1199){
// Medium Device
return "md"
} else {
// Large Device
return "lg"
}
};
现在我们已经设置了函数,我们可以调用它并存储值:
var device = getBrowserWidth();
你的问题是
如果浏览器在手持设备上,我希望运行不同的脚本。
现在我们有了设备信息,剩下的就是if语句:
if(device === "xs"){
// Enter your script for handheld devices here
}
下面是CodePen的示例:http://codepen.io/jacob-king/pen/jWEeWG