有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。
jQuery$.browser函数不是我想要的。
当前回答
一种简单有效的内衬:
function isMobile() { return ('ontouchstart' in document.documentElement); }
然而,上述代码没有考虑到带有触摸屏的笔记本电脑的情况。因此,我提供了基于@Julian解决方案的第二个版本:
function isMobile() {
try{ document.createEvent("TouchEvent"); return true; }
catch(e){ return false; }
}
其他回答
我用这个
if(navigator.userAgent.search("mobile")>0 ){
do something here
}
我知道这个老问题,有很多答案,但我认为这个功能很简单,将有助于检测所有移动设备、平板电脑和计算机浏览器,它就像一个魅力。
function Device_Type()
{
var Return_Device;
if(/(up.browser|up.link|mmp|symbian|smartphone|midp|wap|phone|android|iemobile|w3c|acs\-|alav|alca|amoi|audi|avan|benq|bird|blac|blaz|brew|cell|cldc|cmd\-|dang|doco|eric|hipt|inno|ipaq|java|jigs|kddi|keji|leno|lg\-c|lg\-d|lg\-g|lge\-|maui|maxo|midp|mits|mmef|mobi|mot\-|moto|mwbp|nec\-|newt|noki|palm|pana|pant|phil|play|port|prox|qwap|sage|sams|sany|sch\-|sec\-|send|seri|sgh\-|shar|sie\-|siem|smal|smar|sony|sph\-|symb|t\-mo|teli|tim\-|tosh|tsm\-|upg1|upsi|vk\-v|voda|wap\-|wapa|wapi|wapp|wapr|webc|winw|winw|xda|xda\-) /i.test(navigator.userAgent))
{
if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent))
{
Return_Device = 'Tablet';
}
else
{
Return_Device = 'Mobile';
}
}
else if(/(tablet|ipad|playbook)|(android(?!.*(mobi|opera mini)))/i.test(navigator.userAgent))
{
Return_Device = 'Tablet';
}
else
{
Return_Device = 'Desktop';
}
return Return_Device;
}
这里有一个函数,您可以使用它来获得关于您是否在移动浏览器上运行的正确/错误答案。是的,这是浏览器嗅探,但有时这正是您需要的。
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;
}
http://www.w3schools.com/jsref/prop_nav_useragent.asp
按平台名称筛选。
Ex:
x = $( window ).width();
platform = navigator.platform;
alert(platform);
if ( (platform != Ipad) || (x < 768) ) {
}
^^
屏幕可能位于分辨率较小的桌面上,也可能位于分辨率较宽的手机上,因此,结合本问题中的两个答案
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')
}