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

标签 javascript android ios touchscreen

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

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

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

我怎样才能做到这一点?

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

最佳答案

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

关于javascript - 如何使用javascript检测仅智能手机和平板电脑的onclick事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34554373/

相关文章:

javascript - 从 TEXTAREA 获取值

android - Cordova 插件媒体 : Parse ".amr" Audio File on nodejs server

android - 有没有办法禁用纵向颠倒方向但启用常规纵向和横向方向?

objective-c - 应用程序包中的本地化文件

ios - 将方法从一个类覆盖到另一个类

javascript - 在正则表达式中使用变量 (jQuery)

javascript - 在创建electronicjs自动启动应用程序时遇到问题

javascript - React Native AXIOS方法GET response.data显示为空

android - MPChart 饼图周围的边框

ios - 在解析iOS中搜索1000多个查询