2011-01-28 46 views
11

假設文本顯示HTML網頁上進行如下(只是一個詞太長,不適合在一行上):如何避免使用CSS的最後一行中的單詞?

Lorem ipsum dolores amet foo 
bar 

如何才能避免與CSS出現在最後一行的最後一個字,和強制兩個(或更多)?

Lorem ipsum dolores amet 
foo bar 

回答

19

我不認爲你可以在純CSS中做到這一點。

你將不得不要麼把在過去的兩個詞之間的非打破空間:

foo bar 

或把最後兩個字成span

<span style="white-space: nowrap">foo bar</span> 
+4

+1。這種事情可以通過一個小小的JavaScript輕鬆實現自動化。 – keithjgrant 2011-01-28 01:16:52

2

不能爲用CSS完成,但Shaun Inman寫了一段非常有用的Javascript來幫助這一點:

http://www.shauninman.com/archive/2006/08/22/widont_wordpress_plugin

這是一個WordPress插件,但有很多非WordPress的克隆。

+0

肖恩的這篇文章是從2006年開始的,在我看來有點依賴。 – bart 2011-01-28 20:43:26

+3

年齡並不重要 - 這是一個非常簡單的Javascript模式,它在設計時起作用,並且一直持續到今天。 – 2011-01-28 23:40:15

+2

不明白爲什麼此答案被拒絕。儘管已經有幾年了,Shaun的代碼仍然非常相關。似乎有點荒謬的是,只因爲它的年齡而忽略了一件事的有效性。 – 2011-02-01 11:20:21

3

就寫了這個免費的依賴,JS片段,將解決這一非常問題

https://github.com/ajkochanowicz/BuddySystem

本質上講,這是源代碼

var buddySystem=function(e){var n=[],r=[] 
n=e.length?e:n.concat(e),Array.prototype.map.call(n,function(e){var n=String(e.innerHTML) 
n=n.replace(/\s+/g," ").replace(/^\s|\s$/g,""),r.push(n?e.innerHTML=n.replace(new RegExp("((?:[^ ]*){"+((n.match(/\s/g)||0).length-1)+"}[^ ]*) "),"$1&nbsp;"):void 0)})} 

,你可以通過做這個

實現它
objs = document.getElementsByClassName('corrected'); 
buddySystem(objs); 

現在你永遠不會有一個對於任何帶有corrected類的標籤,本身就是單詞。

如果需要,也可以使用jQuery。

$(".corrected").buddySystem()

退房的鏈接,所有的可能性。

4

我不認爲它可以在CSS中完成,但這是我想出來解決每行一個字的問題。它將用所有匹配元素的非破壞空間替換最後的n個空格。

https://jsfiddle.net/jackvial/19e3pm6e/2/

function noMoreLonelyWords(selector, numWords){ 

     // Get array of all the selected elements 
     var elems = document.querySelectorAll(selector); 
     var i; 
     for(i = 0; i < elems.length; ++i){ 

     // Split the text content of each element into an array 
     var textArray = elems[i].innerText.split(" "); 

     // Remove the last n words and join them with a none breaking space 
     var lastWords = textArray.splice(-numWords, numWords).join("&nbsp;"); 

     // Join it all back together and replace the existing 
     // text with the new text 
     var textMinusLastWords = textArray.join(" "); 
     elems[i].innerHTML = textMinusLastWords + " " + lastWords; 
     } 
    } 

    // Goodbye lonely words 
    noMoreLonelyWords("p", 3); 
1

如果JavaScript是一種選擇,可以使用typogr.js,一個JavaScript 「typogrify」 執行。這個特定的過濾器被稱爲Widont。

<script src="https://cdnjs.cloudflare.com/ajax/libs/typogr/0.6.7/typogr.min.js"></script> 
<script> 
document.body.innerHTML = typogr.widont(document.body.innerHTML); 
</script> 
</body> 
相關問題