有没有办法检测用户是否在jQuery中使用移动设备?类似于CSS@media属性?如果浏览器在手持设备上,我希望运行不同的脚本。

jQuery$.browser函数不是我想要的。


当前回答

在新版本的chrome(101)解决方案中,使用navigator.platform可能无法运行谷歌支持站点,但有一种更简单的方法来检查设备是否为移动设备。

如果(navigator.userAgentData.mobile==“true”){//移动电话代码console.log('bile');}其他{//PC和笔记本电脑代码console.log(“PC”);}

其他回答

使用此

if( screen.width <= 480 ) { 
    // is mobile 
}

您可以使用媒体查询来轻松处理它。

isMobile = function(){
    var isMobile = window.matchMedia("only screen and (max-width: 760px)");
    return isMobile.matches ? true : false
}

navigator.userAgentData.mobile返回[true|false]

仅使用matchMedia的IE10+解决方案:

const isMobile = () => window.matchMedia('(max-width: 700px)').matches

isMobile()返回布尔值

你可以做这么简单的事情

(window.screen.width < 700) {
    //The device is a Mobile
} else {
    //The device is a Desktop
}