javascript 用于检测触摸/移动设备的各种JavaScript方法

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 用于检测触摸/移动设备的各种JavaScript方法相关的知识,希望对你有一定的参考价值。

// Method 1
var isTouchDevice =
    (('ontouchstart' in window) ||
    (navigator.MaxTouchPoints > 0) ||
    (navigator.msMaxTouchPoints > 0));
if(!isTouchDevice){
    console.log('is not touch');
}else{
    console.log('is touch');
}

// Method 2: Not supported by IE
if(window.matchMedia("(pointer: coarse)").matches) {
    // touchscreen
}


// Method 3: Modernizer way
function is_touch_device() {
  var prefixes = ' -webkit- -moz- -o- -ms- '.split(' ');
  var mq = function(query) {
    return window.matchMedia(query).matches;
  }

  if (('ontouchstart' in window) || window.DocumentTouch && document instanceof DocumentTouch) {
    return true;
  }

  // include the 'heartz' as a way to have a non matching MQ to help terminate the join
  // https://git.io/vznFH
  var query = ['(', prefixes.join('touch-enabled),('), 'heartz', ')'].join('');
  return mq(query);
}

// Method 4 
// Detection logic:
// 1. If Pointer Events are supported, it will just check the navigator.maxTouchPoints property
// 2. If Pointer Events are not supported, it checks the any-pointer:coarse interaction media feature using window.matchMedia.
// 3. Check for Touch Events support
function detectTouchscreen() {
  var result = false;
  if (window.PointerEvent && ('maxTouchPoints' in navigator)) {
    // if Pointer Events are supported, just check maxTouchPoints
    if (navigator.maxTouchPoints > 0) {
      result = true;
    }
  } else {
    // no Pointer Events...
    if (window.matchMedia && window.matchMedia("(any-pointer:coarse)").matches) {
      // check for any-pointer:coarse which mostly means touchscreen
      result = true;
    } else if (window.TouchEvent || ('ontouchstart' in window)) {
      // last resort - check for exposed touch events API / event handler
      result = true;
    }
  }
  return result;
}

以上是关于javascript 用于检测触摸/移动设备的各种JavaScript方法的主要内容,如果未能解决你的问题,请参考以下文章

使用 Javascript 检测触摸屏设备

用于移动触摸屏设备的 Ace 文本编辑器上的慢速滚动

javascript 布尔(true或false)函数,用于检测当前正在浏览网站的移动设备

javascript 使用JS检测触摸设备

检测设备是不是有键盘,或者是触摸设备

javascript http://detectmobilebrowsers.com/ JS脚本的略微修改版本,用于检测移动设备。这包括平板电脑