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

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


当前回答

这不是jQuery,但我发现了这个:http://detectmobilebrowser.com/

它提供了检测多种语言的移动浏览器的脚本,其中一种是JavaScript。这可能会帮助你找到你想要的东西。

但是,由于您使用的是jQuery,您可能需要了解jQuery.support集合。它是用于检测当前浏览器功能的财产集合。文档位于此处:http://api.jquery.com/jQuery.support/

因为我不知道你到底想做什么,所以我不知道其中哪一个最有用。

尽管如此,我认为最好的选择是使用服务器端语言(如果可以选择的话)重定向或编写不同的脚本到输出。由于您并不真正了解移动浏览器x的功能,因此在服务器端执行检测和更改逻辑将是最可靠的方法。当然,如果您不能使用服务器端语言,所有这些都是一个悬而未决的问题:)

其他回答

如果您使用Modernizr,那么很容易使用前面提到的Modernizr.touch。

然而,为了安全起见,我更喜欢使用Moderniz.touch和用户代理测试的组合。

var deviceAgent = navigator.userAgent.toLowerCase();

var isTouchDevice = Modernizr.touch || 
(deviceAgent.match(/(iphone|ipod|ipad)/) ||
deviceAgent.match(/(android)/)  || 
deviceAgent.match(/(iemobile)/) || 
deviceAgent.match(/iphone/i) || 
deviceAgent.match(/ipad/i) || 
deviceAgent.match(/ipod/i) || 
deviceAgent.match(/blackberry/i) || 
deviceAgent.match(/bada/i));

if (isTouchDevice) {
        //Do something touchy
    } else {
        //Can't touch this
    }

如果您不使用Modernizr,您可以简单地将上面的Modernizr.touch函数替换为(document.documentElement中的“ntouchstart”)

还要注意,测试用户代理iemobile将为您提供比Windows Phone更广泛的检测到的Microsoft移动设备。

另请参阅此SO问题

你需要控制大小

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();

很好的回答,谢谢。支持Windows phone和Zune的小改进:

if (navigator.userAgent.match(/Android/i) ||
  navigator.userAgent.match(/webOS/i) ||
  navigator.userAgent.match(/iPhone/i) ||
  navigator.userAgent.match(/iPad/i) ||
  navigator.userAgent.match(/iPod/i) ||
  navigator.userAgent.match(/BlackBerry/) ||
  navigator.userAgent.match(/Windows Phone/i) ||
  navigator.userAgent.match(/ZuneWP7/i)
) {
  // some code
  self.location = "top.htm";
}

结账http://detectmobilebrowsers.com/它为您提供了多种语言的移动设备检测脚本,包括

JavaScript、jQuery、PHP、JSP、Perl、Python、ASP、C#、ColdFusion等

如果你不特别担心小显示器,你可以使用宽度/高度检测。这样,如果宽度小于一定大小,移动网站就会被抛出。这可能不是完美的方法,但对于多个设备来说,这可能是最容易检测到的。您可能需要为iPhone4(大分辨率)设置一个特定的分辨率。