Detect support for meta viewport scaling

2019-07-02 08:50发布

Is it possible to detect whether the browser will scale the website based on the meta viewport element?

2条回答
在下西门庆
2楼-- · 2019-07-02 09:47

There isn't any JavaScript method to detect if the meta viewport will be applied. However, you can check if it was applied via two step process with inline js in the head, with an approach such as:

<head>
<script>
  var clientWidth = document.documentElement.clientWidth;
</script>
<meta name="viewport" content="width=device-width,initial-scale=1">
<script>
  if (clientWidth !== document.documentElement.clientWidth){
  //device or browser support the meta-viewport which just changed the width
  }
</script>
</head>

This works with responsive design in most common case on mobile because the initial/default viewport of mobile devices is 980px (http://www.quirksmode.org/mobile/metaviewport/) which isn't a common desktop screen-with at all. And no current desktop browsers support the meta-viewport.

I am going to use this method as factor to detect a mobile device in that respect. However, its worth noting that there are exceptions. So you can't rely on the above method alone for all devices.

e.g. With the Blackberry Playbook, the default viewport sizes already match the 600x1024 pixel size of device-width, initial-scale=1, so clientWidth will not change despite meta-viewport rescaling.

查看更多
一夜七次
3楼-- · 2019-07-02 09:49

No, the meta viewport element just tells the mobile browser how it should handle the current page. So, it depends a bit what you will do.

If you will catch resize events then you can do it with some javascript:

$(window).resize(function() {
    //resize just happened, pixels changed
});

Or if you just want to add different styles on different screen sizes then use media queries in your css file like:

@media only screen and (min-width : 30em) {
    body{font-size: 125%;}
}

@media only screen and (min-width: 37.5em) {
    body{font-size: 163%;}
} 
查看更多
登录 后发表回答