Determining the width of a webpage in inches

非 Y 不嫁゛ 提交于 2019-12-05 09:10:28

It's a non-trivial problem.

Here's a link to a site that has a function (getUnits) to get the current computed style in a measurement unit of your choice (including inches) http://upshots.org/javascript/javascript-get-current-style-as-any-unit

Using this function, you could check if (getUnits(document.body, "width").inch < 4). The way this function works, for the curious, is by creating a temporary element in the desired measurement space and reading off the ratio to pixels. In this way you let the browser respond based on its own knowledge the device's PPI. So this is sort of a polyfill for window.devicePixelRatio, however browsers mostly lie about their PPI. For these purposes, though, it doesn't matter since they will be applying the same lie to your inch-unit CSS.

Walkinraven

I don't test this on real browsers, but it should work:

  1. set a hidden <div id="screen" style="display:none"> in your HTML.

  2. In CSS, use media query like:

      @media screen
      { div#screen{color: blue;} }
    
      @media screen and (min-width: 13in)
      { div#screen{color: red;} }
    

Then you can read the div#screen color in JS to choose the actions.

Also, you should take windows resize event into JS consideration.

All you can do is read back the current style of a known element. By looking at something such as the width of an outer-wrapper DIV you can determine which stylesheet in your media query is in use.

I think you're looking at the problem from the wrong angle. You shouldn't be thinking about inches. What you need to know is: given the device and browser how many pixels high should my page be?

The answer will lie in keeping a known set of devices and their respective pixel height.

An iPhone 5 is taller than an iPhone 4 for instance, this affects the effect you're going for.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!