【问题标题】:How to detect onclick event only smart phone and tablet using javascript?如何使用 javascript 仅检测智能手机和平板电脑的 onclick 事件?
【发布时间】:2016-01-01 07:26:18
【问题描述】:

如何使用javascript检测onclick事件仅限智能手机和平板电脑?

https://jsfiddle.net/d87zjbLp/3/

我使用此代码,但我只想在智能手机和平板电脑上调用函数myFunction()(不在个人电脑和笔记本电脑上)

我该怎么做?

<script>
function myFunction() {
    alert("test");
}
</script>

【问题讨论】:

    标签: javascript android ios touchscreen


    【解决方案1】:

    https://jsfiddle.net/0ozss4q4/1/

    首先检查是手机还是平板电脑

    function isMobileOrTablet() {
     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/i)
      || navigator.userAgent.match(/Windows Phone/i)
     ) {
      return true;
     }else {
      return false;
     }
    }
    

    然后创建一个仅在手机或平板电脑上运行的主函数

    function onlyMobileAndTablet(callback) {
     if(isMobileOrTablet()) {
      return callback && callback()
     }
    }
    

    然后在你想要的地方调用这个函数

    onlyMobileAndTablet(function() {
     console.log('only mobile or tablet');
    });
    

    或者你可以这样做。

    function isMobileOrTablet(callback) {
         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/i)
          || navigator.userAgent.match(/Windows Phone/i)
         ) {
          return callback && callback(true);
         }else {
          return callback && callback(false);
         }
        }
    

    然后调用函数并查看返回值

    isMobileOrTablet(function(res) {
     if (res) {
      // This is mobile/tablet
     } else {
      // this is not a mobile/tablet
     }
    });
    

    【讨论】:

    • 注意:我编辑了答案,因为我在函数 isMobileOrTablet 的末尾缺少了一个 }
    【解决方案2】:

    您应该只使用“on touchstart”属性。

    也许有一个更适合你的事件,比如 touchend,或者 touchenter;

    http://www.javascriptkit.com/javatutors/touchevents.shtml

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 2013-04-14
      • 1970-01-01
      • 1970-01-01
      • 2012-03-20
      相关资源
      最近更新 更多