如何覆盖设备像素比

8
我制作了一个响应式网站,可以适配不同的屏幕分辨率。我使用了三个不同的媒体查询-从0到640、从640到960和以上。但是,如果我在我的三星Galaxy Note2上打开它,因为它具有像素比2,它会将网站读取为360x640设备,但具有640-960样式。我该如何确保网站以原始分辨率显示?
我在头部中包含了以下内容:
<meta name="viewport" content="width=720, initial-scale=1, maximum-scale=1, user-scalable=no" />

如果我在样式表文件中添加类似于以下内容的代码
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) { 
@viewport {
     max-zoom:50%;
     width:720px;
}
}

在Chrome的仿真模式下可以正常工作,但在实际移动设备上测试时无法正常运行。

编辑: 哇哦... 我找到了一种用JavaScript实现的方法。

document.querySelector("meta[name=viewport]").setAttribute('content', 'width=device-width, initial-scale='+(1/window.devicePixelRatio)+', maximum-scale=1.0, user-scalable=0');

该代码读取设备像素比(device pixel ratio),然后设置initial-scale的值。


这个maximum-scale=1, user-scalable=no不被推荐使用,因为它会导致用户体验变差。 - Paulie_D
@Paulie_D 我知道,但是网站是这样设计的,缩放不是一个好主意,基本上是无法避免的。 - kosijer
谢谢!正是我想要的。如果用户想要显示桌面上看到的屏幕,那么可以调用该JavaScript。有时非常有帮助。 - rsmoorthy
2个回答

3

<!doctype html>
<html>
  <head>
    <title>This is the title of the webpage!</title>
  </head>
  <script>
        function toggleZoomScreen() {
        document.body.style.zoom = (1 / window.devicePixelRatio);
        }
    </script>
  <body onload="toggleZoomScreen()" onresize="toggleZoomScreen()">
    <p>This is an example paragraph. Anything in the <strong>body</strong> tag will appear on the page, just like this <strong>p</strong> tag and its contents.</p>
`<img src="https://c.tenor.com/xlylHMRf90oAAAAj/funny-face.gif" width="50">`
  </body>
</html>

这里有一个示例,无论设备的像素比如何,都保持相同的大小。(感谢Github上的@chrisvfritz提供的最简单的HTML模板。

文档加载时,运行上面的脚本,将body的缩放设置为1除以设备的像素比,从而使文本和图像成为1:1比例。

优点:在不同的设备缩放上进行了测试,效果良好。

缺点:缩放不起作用。


2

我还没有测试过这个,但是尝试更改:

<meta name="viewport" content="width=720, initial-scale=1, maximum-scale=1, user-scalable=no" />

to

<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />

将宽度设置为720可以解释为什么你的640-960样式被应用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接