?
只有一行時(不顯示展開按鈕):
?
話不多說,上碼?
~template?
<el-col :span="24"><el-form-item :label="$t('warningOrgNames_')"><div class="content-box" ref="contanierRef"><div ref="contentRef" id="content" :class="isExpanded ? 'text-expanded' : 'text-ellipsis'">{{ form.informInstitution }}</div><div class="show-more" v-if="shouldShowMore" @click="showMore">{{isExpanded ? '收起' : '查看更多'}}</div></div></el-form-item></el-col>
~js?
import { ref, reactive, watch, nextTick } from "vue";const contentRef = ref(null);const isExpanded = ref(false); // 默認不展開const shouldShowMore = ref(false); // 是否顯示查看更多按鈕const contentMaxHeight = ref(0); // 內容的最大高度// 查看更多按鈕邏輯const showMore = () => {isExpanded.value = !isExpanded.value;};// 檢查元素是否溢出 - 注意,這里不能在onMounted函數進行(會在父組件先組件掛載),還拿不到彈窗里的節點const checkOverflow = async() => {await nextTick();if (contentRef.value) {// 元素內部所有滾動內容的總高度const contentHeight = contentRef.value.scrollHeight;// 計算行高const lineHeight = parseInt(window.getComputedStyle(contentRef.value).lineHeight);const maxLines = 3;// 3行的行高contentMaxHeight.value = lineHeight * maxLines;shouldShowMore.value = contentHeight > contentMaxHeight.value;}
};// 打開彈窗 -- 可通過接收參數data來展示父組件的數據
const openDialog = async (row, data, requestFn) => {visible.value = true;try {...// 需要在打開彈窗獲取到數據時才檢查文本高度
++ checkOverflow()}...
}// 點擊查看更多/收起按鈕時也觸發檢查一下文本高度
++ watch(isExpanded, (val) => {
++ checkOverflow();
++ })// 關閉
const handleCancel = () => {...// 關閉按鈕時重置一下展開按鈕
++ isExpanded.value = false;visible.value = false;
};
~style
.content-box {position: relative;
}
.text-ellipsis {display: -webkit-box;-webkit-box-orient: vertical;-webkit-line-clamp: 3; /* 限制文本顯示為3行 */line-height: 2.5;overflow: hidden;
}
.show-more {position: absolute;color: #409EFF;cursor: pointer;right: 0;bottom: -20px;
}
.text-expanded {-webkit-line-clamp: unset; /* 取消限制 */
}
由于這是封裝后的組件,不能在onMounted函數判斷元素是否溢出,要在打開彈窗獲取到數據時才調用checkOverflow()