文本数字溢出后,按比例缩小,vue组件封装
# 文本数字溢出后,按比例缩小,vue组件封装
<template>
<div ref="containerRef" class="wrapper">
<div ref="contentRef" class="content">
<slot />
</div>
</div>
</template>
<script lang="ts" setup>
let destroyFunc: () => void;
const containerRef = ref<HTMLElement>();
const contentRef = ref<HTMLElement>();
onMounted(() => {
if (!containerRef.value || !contentRef.value) {
return;
}
const resizeObserver = new ResizeObserver((targets) => {
const containerWidth = containerRef.value?.offsetWidth;
const child = containerRef.value?.firstElementChild as HTMLElement;
const contentWidth = contentRef.value?.scrollWidth;
if (containerWidth && contentWidth && containerWidth < contentWidth) {
const scale = containerWidth / contentWidth;
child.style.transform = `scale(${scale})`;
child.style.transformOrigin = 'left';
} else {
child.style.transform = 'none';
}
});
resizeObserver.observe(containerRef.value);
destroyFunc = () => {
resizeObserver.disconnect();
};
});
onBeforeUnmount(() => {
destroyFunc && destroyFunc();
});
</script>
<style lang="scss" scoped>
.wrapper {
width: 100%;
max-width: 100%;
overflow: hidden;
}
.content {
width: auto;
}
</style>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
上次更新: 2023/06/01, 12:40:50