标签选中后,字体加粗厚宽度变化

311 阅读1分钟

在开发中,标签选中加粗是非常常见的场景。但是发现字体变粗的时候,父容宽度会发生改变,尤其是在有背景色的时候,就会出现切换时抖动的情况,下面看下实际场景:

标签未选中

image.png

标签选中

image.png

代码如下:

<template>
  <div
    class="tag text-[14px] font-[500] cursor-pointer"
    :class="{'tag_selected': selected}"
  >
    <span
      :title="title"
      :class="[selected ? 'font-mb' : 'font-ml']"
    >{{ title }}</span>
  </div>
</template>

<script lang="ts" setup>
withDefaults(defineProps<{
  title: string,
  selected: boolean
}>(), {
  title: '',
  selected: false
});
</script>
<style scoped lang="less">
.tag {
  display: inline-flex;
  padding-left: 12px;
  padding-right: 12px;
  line-height: 36px;
  background: #F7F7F7;
  border: 1px solid transparent;
}

.tag_selected {
  border-color:  #000;
}
</style>

解决思路:如果我们在未选中的时候,让选中的样式去撑开宽度,这样未选中选中的宽度就能保持一致了

.tag span::after {
  display: block;
  content: attr(title); // 使用span标签的title属性内容作为填充
  font-family: Muli-Bold,Muli,sans-serif; // 选中后的粗体
  overflow: hidden; // 超出部分隐藏
  visibility: hidden; // 隐藏伪元素的内容
  height: 0; // 防止父容器高度被撑开
}

最终代码如下:

<template>
  <div
    class="tag text-[14px] font-[500] cursor-pointer"
    :class="{'tag_selected': selected}"
  >
    <span
      :title="title"
      :class="[selected ? 'font-mb' : 'font-ml']"
    >{{ title }}</span>
  </div>
</template>

<script lang="ts" setup>
withDefaults(defineProps<{
  title: string,
  selected: boolean
}>(), {
  title: '',
  selected: false
});
</script>
<style scoped lang="less">
.tag {
  display: inline-flex;
  padding-left: 12px;
  padding-right: 12px;
  line-height: 36px;
  background: #F7F7F7;
  border: 1px solid transparent;
}

.tag span::after {
  display: block;
  content: attr(title);
  font-family: Muli-Bold,Muli,sans-serif;
  overflow: hidden;
  visibility: hidden;
  height: 0;
}

.tag_selected {
  border-color:  #000;
}
</style>