2012-10-22 27 views
11

在我的網頁我有固定的寬度,並使用下面的CSS一個div:文本溢出省略號:避免字打破

width: 200px; 
overflow: hidden; 
text-overflow: ellipsis; 
white-space: nowrap; 

省略號工作,問題是,它削減了最後一句話,我希望它將省略號(...)放在整個單詞的最後。例如,如果我有文本:「stackoverflow是最好的」,並且如果它需要在最後切割,我希望它顯示「stackoverflow是...」,而不是「stackoverflow是be ...「

回答

4

恐怕這是不可能的。有一次text-overflow: ellipsis-word,這將做到這一點,但它沒有在瀏覽器中實現,並且它從CSS3草稿中刪除。

0

有一個這樣做的jQuery插件,名爲dotdotdot

它也適用於多行文本,並在文本重排例如文本時迴應。如果屏幕尺寸改變。它還包括智能截斷路徑名,例如http://example.com/some/long/.../path.html


注意的基於寬時序問題在案件的可能性其中寬度變化或變成方式插件可能沒有想到,例如,如果文本最初是隱藏的,或者如果它改變字體(不可用例如在某些瀏覽器上加載網頁字體)。可能需要重新申請或在此類更改後應用。

但99%的時間,插件似乎快速和健壯。

1

當然這是可能的。 (如果你願意改變你的標記位。)

https://jsfiddle.net/warphLcr/

<style> 
    .foo { 
    /* Make it easy to see where the cutoff point is */ 
    border: 2px solid #999; 

    padding-right: 18px; /* Always have room for an ellipsis */ 
    width: 120px; 
    height: 1.1em; /* Only allow one line of text */ 
    overflow: hidden; /* Hide all the text below that line */ 
    background-color: #fff; /* Background color is required */ 
    } 
    .foo > span { 
    display: inline-block; /* These have to be inline block to wrap correctly */ 
    position: relative; /* Give the ellipsis an anchor point so it's positioned after the word */ 
    background-color: #fff; /* Cover the ellipsis of the previous word with the same background color */ 
    white-space: pre; /* Make sure the only point where wrapping is allowed is after a whole word */ 
    } 
    .foo > span:after { 
    position: absolute; /* Take the ellipsis out of the flow, so the next item will cover it */ 
    content: "…"; /* Each span has an ellipsis */ 
    } 
    .foo > span:last-child:after { 
    content: ""; /* Except for the last one */ 
    } 
</style> 

<div class="foo"> 
    <!-- These *must not* have white space between them, or it will collapse to a space before the next word, and the ellipsis will become visible --> 
    <span>stackoverflow</span><span> is</span><span> the</span><span> best</span> 
</div> 
+0

該代碼沒有ellipsize一個大長詞溢出。因此,如果你想這樣做,請將每個單詞放在另一個跨度中(因此每個單詞都在兩個跨度內),並添加以下代碼: –

+0

.foo> span> span如果您想要一個跨度,則必須使用兩個跨度一個巨字的省略號*/ display:inline-block; max-width:100%; 溢出:隱藏; } .foo> span { max-width:100%; ... [其餘代碼] –