像素设备比
- 解决一像素变框的问题首先要了解一下什么是设备像素比(DPR)
设备像素比(dpr) 是指在移动开发中1个css像素占用多少设备像素,如2代表1个css像素用2x2个设备像素来绘制。
想要具体了解 CSS像素、物理像素、逻辑像素、设备像素比、PPI、Viewport等概念 通过这篇文章进行了解:
CSS像素、物理像素、逻辑像素、设备像素比、PPI、Viewport
如果对设备像素比并没有太多了解,通过本文章依然可以对解决一像素边框问题得到完整的思路
开始
通俗来讲我们可以通过获取当前设备的设备像素比来设置边框的宽度为几个物理点
- 这里我们通过stylus进行一像素边框函数的封装,用scc3的语法来获取当设备的设备像素比并通过动画效果控制边框的宽度缩放
实现思路(简易版)
- 先不进行封装,在样式上先实现一下,我们默认当前的dpr为2,先不进行像素设备比的获取
<template>
<div class="container">
<div class="targetBox"></div>
</div>
</template>
<style lang="stylus" scoped>
.container {
height: 100%;
display: flex;
flex-direction: column;
flex: 1;
align-items: center;
justify-content: center;
.targetBox {
height: 2rem;
width: 2rem;
background-color: #ccc;
position relative
// border 1px solid #f00
&::after { // 在要生成1像素边框的元素上定义一个伪元素
content: ''; // 微元素的内容
position: absolute;
top: 0;
left: 0;
border: solid 1px #f00; // 设置边框的样式和宽度为1PX
width: 200%; // 将微元素设置为当前元素的二倍,只是将元素放大,边框并没有放大
height: 200%;
transform: scale(0.5); // 然后以缩小到原来的一半,边框却跟着缩小了一半
transform-origin: 0 0; // 动画缩放的轴心设置为左上角
}
}
}
</style>
添加伪类前的一像素边框效果 | 添加伪类后一像素边框效果 |
---|---|
![]() | ![]() |
stylus函数封装一像素边框(完整版)
$border(width = 0, color = #ccc, style = solid, radius = 0)
position relative
border-radius radius
&::after
pointer-events none
position absolute
z-index 999
top 0
left 0
content ""
border-color color
border-style style
border-width width
@media (max--moz-device-pixel-ratio: 1.49),
(-webkit-max-device-pixel-ratio: 1.49),
(max-device-pixel-ratio: 1.49),
(max-resolution: 143dpi),
(max-resolution: 1.49dppx)
width 100%
height 100%
transform scale(1)
border-radius radius
@media (min--moz-device-pixel-ratio: 1.5) and (max--moz-device-pixel-ratio: 2.49),
(-webkit-min-device-pixel-ratio: 1.5) and (-webkit-max-device-pixel-ratio: 2.49),
(min-device-pixel-ratio: 1.5) and (max-device-pixel-ratio: 2.49),
(min-resolution: 144dpi) and (max-resolution: 239dpi),
(min-resolution: 1.5dppx) and (max-resolution: 2.49dppx)
width 200%
height 200%
transform scale(0.5)
border-radius radius * 2
@media (min--moz-device-pixel-ratio: 2.5),
(-webkit-min-device-pixel-ratio: 2.5),
(min-device-pixel-ratio: 2.5),
(min-resolution: 240dpi),
(min-resolution: 2.5dppx)
width 300%
height 300%
transform scale(0.3333333)
border-radius radius * 3
transform-origin 0 0