一像素边框线的实现方式

103 阅读1分钟
  • 苹果手机的一像素很多时候看起来比较清爽,但是它的devicePixelRatio是等于2,所以要实现一像素,可以用缩放的方式.缩放一倍
  • 其他的安卓手机有的devicePixelRatio是等于3,还有devicePixelRatio是等于4的等等,都是同样的思路

附上代码示例,这里使用的sass

<!--  -->
<script setup>
import { ref, reactive } from "vue";
import searchIcon from "@/assets/images/search.png";
defineProps(["outer-bg", "inner-bg", "has-border"]);
</script>
<template>
  <div class='searchbar-wrapper' :style="{backgroundColor: outerBg}">
    <div :style="{backgroundColor: innerBg}" :class="{'hasborder': hasBorder}">
      <img :src="searchIcon" alt="">
      <p>这是一个搜索框,带一像素边框</p>
    </div>
  </div>
</template>

<style lang='scss' scoped>
@import '@/assets/border.scss';
.searchbar-wrapper {
  padding: 10px 15px;
  //  background-color: #f5f5f5;
  > div {
    width: 100%;
    height: 40px;
    // background-color: #fff;
    border-radius: 5px;
    display: flex;
    align-items: center;
    justify-content: center;
    &.hasborder {
      // border: 1px solid red;
      // 实现实现一像素的代码封装在这个函数里面
     @include border(1px, blue, solid, 4px);//$width, $color, $style, $radius
    }
    img {
      width: 20px;
    }
  }
}
</style>

封装在这里

@mixin border ($width: 1px, $color: red, $style:solid, $radius:5px) {
  position: relative;

  &::after {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    // border: 1px solid blue;
    border-width: $width;
    border-color: $color;
    border-style: $style;
    border-radius: $radius;
    z-index: 999;

    // 每种手机的devicePixelRatio的参数不一样,所以可以用媒体查询来判断,
    //在浏览器控制台 window.devicePixelRatio 查看
    @media screen and (-webkit-max-device-pixel-ratio: 1.49) {
      width: 100%;
      height: 100%;
    }

    @media screen and (-webkit-min-device-pixel-ratio: 1.5) and (-webkit-max-device-pixel-ratio: 2.49) {
      width: 200%;
      height: 200%;
      transform: scale(0.5);
    }

    @media screen and (-webkit-min-device-pixel-ratio: 2.5) {
      width: 300%;
      height: 300%;
      transform: scale(0.333);

    }
    transform-origin: 0 0;
  }
}