移动端一像素边框和2x和3x图的解决方案

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);
        }
      }
}

使用

  1. 需要在标签上使用属性class = "border-1px"
  2. 在CSS中调用混合.top-border-1px(@color)然后传递颜色

2.2 使用JS

  • 使用JS我们主要操作meta标签

步骤

  1. 获取设备像素比,使用window.devicePixelRatio
  2. 获取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的图片我们只需要把后缀名修改一下就可以了
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值