简体   繁体   中英

Finding screen width of HD device with JavaScript

I need to find the screen width of a device with JavaScript, I am unable to change the html and do not want to inject the meta viewport tag before doing so. Essentially I need to detect whether the device width is below 600px (in CSS pixels).

I have seen various recommendations but unfortunately I am getting different behaviour between iOS Safari and the default Android browser:

Command                                           iPhone4     GalaxyS3
------------------------------------------------------------------------
window.devicePixelRatio                           2           2      
window.innerWidth                                 982         626  
window.outerWidth                                 326         720
screen.width                                      320         720 
screen.availWidth                                 320         720  
matchMedia('(max-width: 599px)').matches          false       false
matchMedia('(max-device-width: 599px)').matches   true        false

Unfortunately the inconsistencies of the above values means I don't seem to be able to do it with JavaScript (eg I could divide screen.width by window.devicePixelRatio on Android, but this would then be incorrect on iOS).

Is there a reliable, cross browser way of doing this?

You could try using Verge viewport utility. It's an open source library. Then you could simply use:

$.viewportW() // Get the viewport width in pixels.

Hope this helps!

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