1 原理
- 利用媒体查询或者JS将边框进行缩放
- 我们一般会使用媒体查询和缩放来解决1像素边框和2x和3x图的问题,这里我们使用less来解决
2 一像素边框
2.1 使用媒体查询
定义
- 我们可以把一下代码放到一个
mixin.less
文件中
.bottom-border-1px(@color){
position relative
border none
&:after{
content :'';
position: absolute;
left: 0;
bottom: 0;
width: 100%;
height: 1px;
background-color: @color;
}
}
.top-border-1px(@color){
position: relative;
&::before{
content: '';
position :absolute;
z-index :200;
left :0;
top :0;
width :100%;
height :1px;
background-color: @color;
}
}
//根据像素比缩放1px像素边框
@media only screen and (-webkit-device-pixel-ratio: 2 ){
.border-1px{
&::before{
transform: scaleY(.5);
}
}
}
@media only screen and (-webkit-device-pixel-ratio: 3 ){
.border-1px{
&::before{
transform: scaleY(.333333);
}
}
}
使用
- 需要在标签上使用属性
class = "border-1px"
- 在CSS中调用混合
.top-border-1px(@color)
然后传递颜色
2.2 使用JS
- 使用JS我们主要操作
meta
标签
步骤
- 获取设备像素比,使用
window.devicePixelRatio
- 获取
meta
标签,操作缩放属性
// 获取设备像素比
const dr = window.devicePixelRatio
// 获取meta标签
const meta = document.querySelector("meta[name='viewport']")
const scale = 1/dr
meta.content = "width=device-width,initial-scale=" + scale
- 这样我们就达到了缩放的目的
- 但是他是将所有的像素都缩放了,有没有其他的好的方法呢?
与rem一起使用
- 当我们使用rem时,是没有缩放的单位
- 使用px的时候是缩放的单位,代码如下,我们只是将缩小后的元素有放大回来
(function(){
var dpr = window.devicePixelRatio||1;
var styleNode = document.createElement("style");
var w = document.documentElement.clientWidth*dpr/16;
styleNode.innerHTML="html{font-size:"+w+"px!important}";
document.head.appendChild(styleNode);
var scale = 1/dpr;
var meta = document.querySelector("meta[name='viewport']");
meta.content="width=device-width,initial-scale="+scale;
})()
2x与3x图
.bg-image(@url){
background-image:url("@{url}@2x.jpg");
@media (-webkit-min-device-pixel-ratio: 3),(min-device-pixel-ratio: 3){
background-image: url( "@{url}@3x.jpg");
}
}
- 如果是
.png
的图片我们只需要把后缀名修改一下就可以了