有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
仅使用matchMedia的IE10+解决方案:
const isMobile = () => window.matchMedia('(max-width: 700px)').matches
isMobile()返回布尔值
其他回答
我使用这个解决方案,它在所有设备上都很好:
if (typeof window.orientation !== "undefined" || navigator.userAgent.indexOf('IEMobile') !== -1) {
//is_mobile
}
此外,我建议使用小型JavaScript库Bowser,yes no r。它基于navigator.userAgent,对所有浏览器(包括iPhone、Android等)都进行了测试。
https://github.com/ded/bowser
你可以简单地说:
if (bowser.msie && bowser.version <= 6) {
alert('Hello China');
} else if (bowser.firefox){
alert('Hello Foxy');
} else if (bowser.chrome){
alert('Hello Silicon Valley');
} else if (bowser.safari){
alert('Hello Apple Fan');
} else if(bowser.iphone || bowser.android){
alert('Hello mobile');
}
如果你不特别担心小显示器,你可以使用宽度/高度检测。这样,如果宽度小于一定大小,移动网站就会被抛出。这可能不是完美的方法,但对于多个设备来说,这可能是最容易检测到的。您可能需要为iPhone4(大分辨率)设置一个特定的分辨率。
mobiledetect.net怎么样?
其他解决方案似乎过于基础。这是一个轻量级的PHP类。它使用用户代理字符串和特定的HTTP标头来检测移动环境。您还可以通过使用任何第三方插件从Mobile Detect中获益:WordPress、Drupal、Joomla、Magento等。
这里有一个函数,您可以使用它来获得关于您是否在移动浏览器上运行的正确/错误答案。是的,这是浏览器嗅探,但有时这正是您需要的。
function is_mobile() {
var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry'];
for(i in agents) {
if(navigator.userAgent.match('/'+agents[i]+'/i')) {
return true;
}
}
return false;
}