移动设备检测,我做错了什么?

时间:2016-08-31 22:03:55

标签: javascript

我使用此代码检测移动设备以显示下载按钮:

    function detectDevice() {
    var kindle = navigator.userAgent.match(/(Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI)/i) != null;
    var android = navigator.userAgent.match(/Android/i) != null;
    var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);

    if ( kindle)
    { 
    document.getElementById("android_btn").className += " hide"; 
    document.getElementById("ios_btn").className += " hide"; 
    }
            else if (iOS)
            { 
            document.getElementById("android_btn").className += " hide"; 
            document.getElementById("kindle_btn").className += " hide"; 
            }
                    else if (android)
            {
            document.getElementById("ios_btn").className += " hide"; 
            document.getElementById("kindle_btn").className += " hide"; 
            }
    { // do nothing...show both }
        detectDevice();
    }}

它没有显示正确设备的右键,它显示任何设备的两个按钮。

1 个答案:

答案 0 :(得分:0)

除了缺少else语句之外,您还必须将函数绑定到onloadonclick事件,以使代码生效。

<body onload="detectDevice()">

编辑:

示例:

<!doctype html>
<html lang="en">
 <head>
  <title>Document</title>
  <style>
  .hide { display: none; }
  </style>
  <script type="text/javascript">
  <!--
    function detectDevice() {
    var kindle = navigator.userAgent.match(/(Kindle|Silk|KFTT|KFOT|KFJWA|KFJWI|KFSOWI|KFTHWA|KFTHWI|KFAPWA|KFAPWI)/i) ? true : false;
    var android = navigator.userAgent.match(/Android/i) ? true : false;
    var iOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
    if (kindle)
    { 
        document.getElementById("android_btn").className += " hide"; 
        document.getElementById("ios_btn").className += " hide"; 
    }
    else if (iOS)
    { 
        document.getElementById("android_btn").className += " hide"; 
        document.getElementById("kindle_btn").className += " hide"; 
    }
    else if (android)
    {
        document.getElementById("ios_btn").className += " hide"; 
        document.getElementById("kindle_btn").className += " hide"; 
    }
    else {
        alert("We don't support desktop yet!");
    }
}

  //-->
  </script>
 </head>
 <body onload="detectDevice()">
  <input id="android_btn" type="button" value="Android Download" onclick="">
  <input id="ios_btn" type="button" value="IOS Download" onclick="">
  <input id="kindle_btn" type="button" value="Kindle Download" onclick="">
 </body>
</html>