第一种思路
用js算出来当前手机端的dpr值,如果是2,则缩放为0.5,如果是3,则缩放为0.333,这样你写的px是1px,这个1px是相对单位,在dpr为2的时候相当于2个物理像素,在dpr为3的时候相当于3物理像素,但是由于缩放了视口,所以又变回了1物理像素
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!-- 这一行不写,由js动态生成 -->
<!-- <meta name="viewport" content="width=device-width, initial-scale=1.0"> -->
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<script>
function setViewport() {
var dpr = window.devicePixelRatio
var scale = (1 / dpr).toFixed(5)
var metaNode = document.createElement('meta')
metaNode.setAttribute('name', 'viewport')
metaNode.setAttribute('content', `width=device-width, initial-scale=${scale},user-scalable=no,maximum-scale=${scale},minimum-scale=${scale}`)
document.head.appendChild(metaNode)
}
window.onresize = setViewport
setViewport()
</script>
<style>
.demo{
margin-top: 100px;
width:400px;
height:1px;
background:black;
}
</style>
</head>
<body>
<div class="demo"></div>
</body>
</html>
第二种思路
使用媒体查询+-webkit-min-device-pixel-ratio属性
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0,user-scalable=no,maximum-scale=1.0,minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.demo{
margin-top: 100px;
width:400px;
height:1px;
background:black;
}
@media screen and (-webkit-min-device-pixel-ratio:2){
.demo{
transform:scaleY(0.5)
}
}
@media screen and (-webkit-min-device-pixel-ratio:3){
.demo{
transform:scaleY(0.3333333)
}
}
</style>
</head>
<body>
<div class="demo"></div>
</body>
</html>