簡體   English   中英

如何使用JavaScript檢測僅智能手機和平板電腦的onclick事件?

[英]How to detect onclick event only smart phone and tablet using javascript?

如何使用javascript僅檢測智能手機和平板電腦的onclick事件?

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

我使用此代碼,但我只想在智能手機和平板電腦上調用函數myFunction() (在PC和筆記本電腦上不調用)

我怎樣才能做到這一點 ?

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

您應該只使用“ on touchstart”屬性。

也許有一個更好的事情可以滿足您的需求,例如touchend或touchenter。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM