2

I try to use javascript to get mobile device viewport size, here I found some nice answer on the stackoverflow:

They both recommend using window.innerHeight and window.innerWidth to get viewport size like this:

var w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0)
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0)

But I found this way sometime can not be accurate, when the device's browser have tool bar or address bar. So I figure out a way using devicePixelRatio to get mobile device viewport size:

if (window.devicePixelRatio) {
    var physicsWidth = window.screen.width;
    var physicsHeight = window.screen.height;

    var viewportWidth = physicsWidth / window.devicePixelRatio;
    var viewportHeight = physicsHeight / window.devicePixelRatio;
}

Is this way OK to get viewport size?

Community
  • 1
  • 1
hh54188
  • 14,887
  • 32
  • 113
  • 184

0 Answers0