What's the best way to detect a 'touch screen' device using JavaScript?

后端 未结 30 2457
花落未央
花落未央 2020-11-21 23:50

I\'ve written a jQuery plug-in that\'s for use on both desktop and mobile devices. I wondered if there is a way with JavaScript to detect if the device has touch screen capa

30条回答
  •  有刺的猬
    2020-11-22 00:37

    Check out this post, it gives a really nice code snippet for what to do when touch devices are detected or what to do if touchstart event is called:

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

提交回复
热议问题