简体   繁体   中英

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>

Hello, i have this code working fine. I want know if possible add more two screens resolutions ( 1300 and 1200 ).

If access by "mobile" = mydomain/mobile

If access by desktop "resolution 1900 plus" = mydomain/1900

If access by desktop "resolution 1600 till 1899" = mydomain/1600

If access by desktop "resolution 1300 till 1599" = mydomain/1300

If access by desktop "resolution 1024 till 1299" = mydomain/1200

Thanks!!

First of all, a better approach to this is CSS rule @media .

If you want to use javascript simply add if else statements...

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

Also I would suggest reduce function detect() and externalize constants:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM