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

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


当前回答

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

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

其他回答

<script>
  function checkIsMobile(){
      if(navigator.userAgent.indexOf("Mobile") > 0){
        return true;
      }else{
        return false;
      }
   }
</script>

如果您转到任何浏览器,并且尝试获取navigator.userAgent,那么我们将获得如下浏览器信息

Mozilla/5.0(Macintosh;Intel Mac OS X 10_13_1)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/64.0.3282.186 Safari/537.36

如果你在手机上做同样的事情,你会得到关注

Mozilla/5.0(Linux;Android 8.1.0;Pixel Build/OOP6.171019.012)AppleWebKit/537.36(KHTML,类似Gecko)Chrome/61.0.3163.98 Mobile Safari/537.36

每个移动浏览器都会有useragent,其字符串包含“mobile”,所以我在代码中使用上面的代码片段来检查当前的用户agent是否是web/mobile。根据结果,我将进行必要的更改。

看看这篇文章,它提供了一个非常好的代码片段,说明当检测到触摸设备时该怎么做,或者如果调用了touchstart事件,该怎么做:

$(function(){
  if(window.Touch) {
    touch_detect.auto_detected();
  } else {
    document.ontouchstart = touch_detect.surface;
  }
}); // End loaded jQuery
var touch_detect = {
  auto_detected: function(event){
    /* add everything you want to do onLoad here (eg. activating hover controls) */
    alert('this was auto detected');
    activateTouchArea();
  },
  surface: function(event){
    /* add everything you want to do ontouchstart here (eg. drag & drop) - you can fire this in both places */
    alert('this was detected by touching');
    activateTouchArea();
  }
}; // touch_detect
function activateTouchArea(){
  /* make sure our screen doesn't scroll when we move the "touchable area" */
  var element = document.getElementById('element_id');
  element.addEventListener("touchstart", touchStart, false);
}
function touchStart(event) {
  /* modularize preventing the default behavior so we can use it again */
  event.preventDefault();
}

您还可以使用服务器端脚本并从中设置javascript变量。

php中的示例

下载http://code.google.com/p/php-mobile-detect/然后设置javascript变量。

<script>
//set defaults
var device_type = 'desktop';
</script>

<?php
require_once( 'Mobile_Detect.php');
$detect = new Mobile_Detect();
?>

<script>
device_type="<?php echo ($detect->isMobile() ? ($detect->isTablet() ? 'tablet' : 'mobile') : 'desktop'); ?>";
alert( device_type);
</script>

一种简单有效的内衬:

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
}