Javascript屏幕分辨率检测和重定向

时间:2015-03-26 11:04:42

标签: javascript redirect screen resolution detection

<script>
    function detect() {
        var uagent = navigator.userAgent.toLowerCase();
        var mobile = false;
        var search_strings = [
            "iphone",
            "ipod",
            "ipad",
            "series60",
            "symbian",
            "android",
            "windows ce",
            "windows7phone",
            "w7p",
            "blackberry",
            "palm"
        ];

        for (i in search_strings) {
            if (uagent.search(search_strings[i]) > -1)
                mobile = true;
        }

        return mobile;
    }

    if (detect()) 
        window.location = "mydomain/mobile";
</script>

<script type="text/javascript">
    if (screen.width <= 1600) {
        window.location.replace('mydomain/1600');
    }
    if (screen.width > 1900) {
        window.location.replace('mydomain/1900');
    }
</script>

您好,我的代码运行正常。我想知道是否可以添加更多两个屏幕分辨率(1300和1200)。

如果通过&#34;移动&#34; = mydomain / mobile

如果通过桌面访问&#34;解决方案1900加&#34; = mydomain / 1900

如果通过桌面访问&#34;解决方案1600至1899&#34; = mydomain / 1600

如果通过桌面访问&#34;解决方案1300至1599&#34; = mydomain / 1300

如果通过桌面访问&#34;分辨率1024到1299&#34; = mydomain / 1200

谢谢!

1 个答案:

答案 0 :(得分:0)

首先,更好的方法是CSS rule @media

如果您想使用javascript,只需添加if else语句......

if (screen.width >= 1900) {
    window.location.replace('mydomain/1900');
} else if (screen.width >= 1600 && screen.width < 1900) {
    window.location.replace('mydomain/1600');
} else if (screen.width >= 1300 && screen.width < 1600) {
    window.location.replace('mydomain/1300');
} else if (screen.width >= 1024 && screen.width < 1200) {
    window.location.replace('mydomain/1024');
} else {
    alert("error");
}

我还建议减少function detect()并外化常量:

var uagent = navigator.userAgent.toLowerCase();
var mobile = false;
var search_strings = [
"iphone",
"ipod",
"ipad",
"series60",
"symbian",
"android",
"windows ce",
"windows7phone",
"w7p",
"blackberry",
"palm"
];

function detect() {
    for (i in search_strings) {
        if (uagent.search(search_strings[i]) > -1){  
            mobile = true;
            return mobile;
        }
    }
    return mobile;
}