Javascript - 根据设备更改按钮图像

时间:2012-10-25 17:45:14

标签: javascript android jquery ios button

我正在尝试显示正确的按钮和链接,具体取决于用户浏览页面的设备。如果android显示android app store按钮,如果ios显示apple store按钮。

我似乎无法让它完全交换,即使我正在使用默认功能将它从android交换到苹果按钮。

以下是代码:

<html>
<head>
    <script type="text/javascript">

        var uagent = navigator.userAgent.toLowerCase();
        var apple = "/images/ios.jpg";
        var android = "/images/android.jpg"


        function DetectDevice() {
            var but = document.getElementById("AppButton");
            if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) {
                toswap.src = apple;
                alert("apple");
            } else if(useragent.search("android")) {
                toswap.src = android;
                alert("android");
            }
            but.src = apple;
        }
        DetectDevice();
    </script>

    <title>Device Detection</title>
</head>

<div id="butttons">
    <img src="images/android.jpg" name = "AppButton" id="AppButton"/>
</div>

3 个答案:

答案 0 :(得分:0)

两个问题:

首先,您的功能需要在按钮加载后运行,因为

document.getElementById("AppButton");

此刻暂时没有回复。

其次,您应该将toswap.src的2个实例更改为but.src

答案 1 :(得分:0)

我不知道var toswap所指的位置。试试这个:

        var uagent = navigator.userAgent.toLowerCase();
        var apple = "/images/ios.jpg";
        var android = "/images/android.jpg"


        function DetectDevice() {
            var but = document.getElementById("AppButton");
            if(useragent.search("iphone") || useragent.search("ipod") || useragent.search("ipad")) {
                but.src = apple;
                alert("apple");
            } else if(useragent.search("android")) {
                but.src = android;
                alert("android");
            } else{
                but.src = apple; // this is default
            }
        }

    </script>

<div id="butttons">
    <img src="images/android.jpg" onload="DetectDevice();" name = "AppButton" id="AppButton"/>
</div>

答案 2 :(得分:0)

useragent也未定义。您可能打算使用您定义的uagent,或者您可能打算重命名您的变量。