❓ 在开发h5页面的时候,常常会需要展示各种文案,前端开发会根据UI出的设计图去实现。这里列出的是单行文本的展示,当文本的宽度超出了可视页面宽度的时候,会出现什么情况呢?
- 一行只放一种类型的文本,文本会超出元素展示
- 一行放了多种类型的文本,文本会覆盖其他元素,错乱展示
❎ 错误展示:
✅ 正确展示:
除了上面列出的2种展示方式,还会有其他的情况么?
答案肯定是有的。能想到的还有很多,举例说明
- 超出宽度换行展示,不滚动(没有最大高度)
- 超出宽度换行展示,滚动(有最大高度)
- 超出宽度换行展示,超过几行隐藏,并展示缩略符
上面的情况算是多行文本了,重点不在这儿,就没详细说明,不过设计成公共组件的时候还是需要把能想到的情况都需要考虑进去。
需要实现的2种展示方式是:
- 单行文本超出宽度自动隐藏,并展示缩略符
- 单行文本超出宽度自动缩小字体
自动缩小字体后,会导致在页面上看不清楚么?
会,所以设计的时候需要设置最小字体。但是设置最小字体后,还是会出现字体超出的情况,此时要考虑是隐藏还是换行展示。
3.1、自动隐藏
单行文本超出宽度自动隐藏,并展示缩略符
第一种:-webkit-line-clamp会有兼容性的问题,需要考虑不同浏览器的情况。
1display: -webkit-box;
2-webkit-line-clamp: 1; // 单行文本
3-webkit-box-orient: vertical;
4overflow: hidden;
第二种:必须设置宽度,否则不生效
1width: 100px;
2overflow: hidden;
3white-space: nowrap;
4text-overflow: ellipsis;
3.2、自动缩小
单行文本超出宽度自动缩小字体
本块的难点:就是如何计算出最合适的字体?
公式 =(可视宽度 - 内边距 * 2)/ 滚动宽度 * 基准字号
=(offsetWidth - padding * 2)/ scrollWidth * basicFontSize
4.1、组件封装
1<template>
2 <!-- 单行文本超过固定宽度 缩小 -->
3 <!-- 单行文本超过固定宽度 隐藏展示缩略点 :key="`text-${uniqueId}`" -->
4 <div
5 ref="text"
6 :class="[hidden ? 'text-comp' : '']"
7 >
8 {{ isOk ? text : '' }}
9 <p
10 ref="computeText"
11 :class="['compute-text']"
12 :style="{
13 fontSize: `${basicFontSize}px`,
14 display: isOk ? 'none' : '',
15 }"
16 >
17 <span>{{ text }}</span>
18 </p>
19 </div>
20</template>
21
22<script>
23 export default {
24 name: 'TextComp',
25 props: {
26 text: {
27 type: [String, Number, Boolean],
28 default: '',
29 },
30
31 hidden: {
32 type: Boolean,
33 default: false,
34 },
35
36 minFontSize: {
37 type: Number,
38 default: 8,
39 }
40 },
41 data() {
42 return {
43 isOk: this.hidden,
44 paddingRight: 4,
45 basicFontSize: 16,
46 }
47 },
48 watch: {
49 text: {
50 handler(value) {
51 if (value && !this.hidden) {
52 this.$nextTick(() => {
53
54 this.setElSize();
55 })
56 }
57 },
58 immediate: true,
59 deep: true,
60 }
61 },
62 methods: {
63 setElSize () {
64 const setNewElSize = (size) =>{
65 const textElement = this.$refs.text;
66 textElement.style.fontSize = `${size}px`;
67 if (size === this.minFontSize) {
68 textElement.style.whiteSpace = `nowrap`;
69 textElement.style.overflow = `hidden`;
70 textElement.style.textOverflow = `ellipsis`;
71 }
72 this.isOk = true;
73 }
74
75 const element = this.$refs.computeText;
76 const actualWidth = element?.offsetWidth;
77 const scrollWidth = element?.scrollWidth;
78
79 if (scrollWidth > actualWidth) {
80 const size = (actualWidth - this.paddingRight) / scrollWidth * this.basicFontSize;
81 setNewElSize(size >= this.minFontSize ? size : this.minFontSize);
82 } else {
83 this.isOk = true;
84 }
85 }
86 },
87 }
88</script>
89
90<style scoped lang="less">
91 .text-comp {
92 width: 100%;
93 overflow: hidden;
94 white-space: nowrap;
95 text-overflow: ellipsis;
96 }
97
98 .compute-text {
99 width: 100%;
100 overflow: scroll;
101 visibility: hidden;
102 white-space: nowrap;
103 }
104</style>
个人笔记记录 2021 ~ 2025