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

Javascript Screen Resolution Detection and Redirection

<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 )。

如果通过 "mobile" 访问 = mydomain/mobile

如果通过桌面访问"resolution 1900 plus" = mydomain/1900

如果通过桌面访问"resolution 1600 till 1899" = mydomain/1600

如果通过桌面访问"resolution 1300 till 1599" = mydomain/1300

如果通过桌面访问"resolution 1024 till 1299" = mydomain/1200

谢谢!!

首先,更好的方法是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;
}