Determining the width of a webpage in inches

北城以北 提交于 2019-12-07 02:15:15

问题


I have a CSS stylesheet that uses media queries to change how a page is displayed based on how many inches it is in width (for instance, if it is smaller than 4 inches or being displayed on a handheld device, it assumes a more mobile-friendly LAF).

The problem I have is with its content. On the homepage, there is a dock-style interface that dynamically changes height based on the current height and width of the window so that the text and items never leave the screen. However, my JS that determines this size does not know when the stylesheet has changed for handheld devices or small screens, so the behavior continues unpredictably in this mode. How can I use JavaScript detect when the page is less than or equal to 4 inches so that I can disable the auto-resizing of the then-reformed dock?


回答1:


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.




回答2:


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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/14242125/determining-the-width-of-a-webpage-in-inches

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