JavaScript實現(xiàn)多行文本溢出
背景:UED給的設(shè)計稿要求。需要實現(xiàn)多行文本溢出省略號的樣式。
原以為是一個簡單的小需求, 框框直接上手。代碼如下
<template> <div class="name-wrap"> <span class="tag bd"> 我是標簽 </span>hhhhhhhhhhhhhhhhhhhh </div> </template> <style> .tag { dispaly: inline-block; } .name-wrap { word-break: break-all; overflow: hidden; text-overflow: ellipsis; display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; } </style>
一切看起來都是嘎嘎完美,雖然我知道這么寫是有兼容問題的,但這個不是我這次關(guān)注的點。重點在于,我還有一個標簽,在大部分手機下都能實現(xiàn)我想要的樣式。但是在高版本的ios(iphone14、iphone15)下,他會默認成單行文本溢出省略號
。我了解到原因是-webkit-line-clamp
屬性的工作原則需要其容器是塊級元素或至少表現(xiàn)得像一個塊級元素。 所以我猜測,有沒有可能在高版本的ios中,這個屬性實現(xiàn)方式有所調(diào)整。
由于我需要的樣式是類似文字環(huán)繞的效果,所以我無法直接給標簽外的文字添加一個span
標簽來改變html
結(jié)構(gòu)。需要加上浮動效果才行。
總結(jié)就是我太菜了,所以我改用了一種比較原始的方法。用js去實現(xiàn)多行文本溢出省略+浮動去實現(xiàn)我想要的效果. 因此記錄一下
<div class="name-wrap"> <span class="tag bd"> 我是標簽 </span> <span class="text-ellipsis" :ref="setItemRef">hhhhhhhhhhhhhhhhhhhh</span> </div> <script lang="ts"> export default defineComponent({ props: { show: Boolean, }, setup(props, ctx) { let showPopup = computed({ get: () => props.show, set: (val: boolean) => ctx.emit("update:show", val), }); const textElements = ref<HTMLElement[]>([]); const setItemRef = (el: any) => { if (el) { textElements.value.push(el); } }; const applyEllipsis = (element: HTMLElement, maxLines: number) => { let text = element.innerHTML; const lineHeight = parseInt(window.getComputedStyle(element).lineHeight); const maxHeight = lineHeight * maxLines; // 不斷減少文本直到其高度小于或等于最大允許高度 while (element.scrollHeight > maxHeight) { text = text.slice(0, -1); element.innerHTML = text + '...'; } } watch(() => showPopup.value, (val: boolean) => { if (val) { requestAnimationFrame(async () => { await nextTick(); // 確保 DOM 已更新 textElements.value.forEach((element) => { applyEllipsis(element, 2); }); }); } }) return { showPopup, setItemRef, } }, }); </script> <style> .name-wrap { font-size: 14px; font-family: PingFangSC-Regular, PingFang SC; font-weight: 400; color: #101112; line-height: 20px; flex: 1; } .tag { float: left; } .text-ellipsis { display: block; word-break: break-all; } </style>
到此這篇關(guān)于JavaScript實現(xiàn)多行文本溢出的文章就介紹到這了,更多相關(guān)JavaScript多行文本溢出內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
微信小程序?qū)崿F(xiàn)收藏與取消收藏切換圖片功能
這篇文章主要介紹了微信小程序?qū)崿F(xiàn)收藏與取消收藏切換圖片功能,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2018-08-08JS實現(xiàn)跟隨鼠標閃爍轉(zhuǎn)動色塊的方法
這篇文章主要介紹了JS實現(xiàn)跟隨鼠標閃爍轉(zhuǎn)動色塊的方法,涉及javascript操作html元素及css樣式的技巧,具有一定參考借鑒價值,需要的朋友可以參考下2015-02-02全面解析JS字符串和正則表達式中的match、replace、exec等函數(shù)
這篇文章主要介紹了全面解析JS字符串和正則表達式中的match、replace、exec等函數(shù)的相關(guān)資料,需要的朋友可以參考下2016-07-07