解决方案
同时通过设置对应viewport的rem基准值,这种方式就可以像以前一样轻松愉快的写1px了。
在devicePixelRatio=2 时,设置meta:
<meta name="viewport" content="width=device-width,initial-scale=0.5, maximum-scale=0.5, minimum-scale=0.5, user-scalable=no">
在devicePixelRatio=3 时,设置meta:
<meta name="viewport" content="width=device-width,initial-scale=0.3333333333333333, maximum-scale=0.3333333333333333, minimum-scale=0.3333333333333333, user-scalable=no">
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<title>移动端1px问题</title>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8" />
<meta name="viewport" id="WebViewport"
content="width=device-width,initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
<style>
html {
font-size: 11px;
}
body {
padding: 1rem;
}
* {
padding: 0;
margin: 0;
}
.item {
padding: 1rem;
border-bottom: 1px solid gray;
font-size: 1.2rem;
}
</style>
<script>
var viewport = document.querySelector("meta[name=viewport]");
var dpr = window.devicePixelRatio || 1;
var scale = 1 / dpr;
//下面是根据设备dpr设置viewport
viewport.setAttribute(
"content", +
"width=device-width," +
"initial-scale=" +
scale +
", maximum-scale=" +
scale +
", minimum-scale=" +
scale +
", user-scalable=no"
);
var docEl = document.documentElement;
var fontsize = 10 * (docEl.clientWidth / 320) + "px";
docEl.style.fontSize = fontsize;
</script>
</head>
<body>
<div class="item">border-bottom: 1px solid gray;</div>
<div class="item">border-bottom: 1px solid gray;</div>
</body>
</html>