div内容溢出后,内容向左悬浮,vue组件封装
# div内容溢出后,内容向左悬浮,vue组件封装
<template>
<div ref="containerRef" class="overflow-left-container">
<div ref="contentRef" class="overflow-left-content">
<slot />
</div>
</div>
</template>
<script setup lang="ts">
const containerRef = ref<HTMLDivElement>();
const contentRef = ref<HTMLDivElement>();
let destroyFunction: () => void;
const processOverflow = () => {
const containerEl = containerRef.value!;
const contentEl = contentRef.value!;
const isOverflow = contentEl.offsetWidth > containerEl.offsetWidth;
if (isOverflow) {
contentEl.classList.add('is-overflow');
} else {
contentEl.classList.remove('is-overflow');
}
};
onMounted(() => {
const el = contentRef.value!;
const observer = new ResizeObserver(() => {
processOverflow();
});
observer.observe(el);
destroyFunction = () => {
observer.disconnect();
};
});
onUnmounted(() => {
if (destroyFunction) {
destroyFunction();
}
});
</script>
<style lang="scss" scoped>
.overflow-left-container {
position: relative;
width: 100%;
height: 100%;
.overflow-left-content {
width: fit-content;
height: 100%;
white-space: nowrap;
&.is-overflow {
position: absolute;
right: 0;
top: 0;
bottom: 0;
}
}
}
</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
52
53
54
55
56
57
58
59
60
61
62
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
52
53
54
55
56
57
58
59
60
61
62
上次更新: 2023/06/01, 12:40:50