简体   繁体   中英

Redirect to mobile page when width is too small

Since my website doesn't look good at all on a small screen, I want to create a JS function that redirects me to a mobile version of the page when width of the screen is smaller than or equal to 800px.

Here is the code for it:

if (screen.width <= 800) {
  document.location ="index_mobile.html";
};

If the code works, then when I shrink down the browser window to 800px wide, the index_mobile.html should show up. But it is not showing up right now. Does anyone know what's going on?

http://jsfiddle.net/RZMmV/

Mobile browsers do not report or use the real device resolution because this would make basically all websites on the internet unusable.

What they do is creating a "virtual screen" that has a resolution that is closer to the resolution of a desktop PC and then will implement zooming on the page.

If you want to know the real device resolution you need to disable automatic scaling done on the device. For example for iOS and Android devices this can be done adding

<meta name="viewport"
      content="width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;"/>

to the <head> section of your page. This informs the browser that the page has been designed for handling low-resolution devices and disables the virtual screen layer.

screen.width will return the width of the monitor, not the window, so you can't just shrink your browser window down to get a different value. To do that, you'll want to use window.outerWidth or something.

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