text-overflow 決定「當文字溢出容器時要如何處理」。它通常不是單獨使用的,而是與 overflow: hidden 和 white-space: nowrap 搭配出三件套。
clipobject.style.textOverflow = "ellipsis"text-overflow: clip | ellipsis | string;
clip:直接裁掉,不出現任何提示。ellipsis:以省略號(…)表示後面還有內容,這是最實用也最常見的選擇。string:用自訂字串取代被裁切的部分。<style>
div.testhovertree {
white-space: nowrap;
width: 12em;
overflow: hidden;
border: 1px solid #000000;
}
div.testhovertree:hover {
text-overflow: inherit;
overflow: visible;
border: 1px solid transparent;
}
</style>
<p>把游標移到下面兩個 div 上,就能看到完整文字。</p>
<p>這個 div 使用 "text-overflow: ellipsis":</p>
<div class="testhovertree" style="text-overflow:ellipsis;">
This is some long text that will not fit in the box.hovertree.com</div>
<p>這個 div 使用 "text-overflow: clip":</p>
<div class="testhovertree" style="text-overflow:clip;">
何問起.This is some long text that will not fit in the box</div>
範例中額外加了一段 :hover 規則,讓滑鼠移入時改回 overflow: visible,使用者就能一次看到完整內容——這是列表、卡片標題被截斷時很實用的折衷做法。
實務提醒:三個屬性缺一不可。少了 white-space: nowrap,文字會換行而不溢出;少了 overflow: hidden,文字會直接衝出容器;少了 text-overflow,則是硬生生成直角裁切。