假设文本在HTML页面上显示如下(只有一个单词太长而无法放在一行上):
Lorem ipsum dolores amet foo
bar
Run Code Online (Sandbox Code Playgroud)
如何用CSS避免最后一个单词出现在最后一行,并强制两个(或更多)?
Lorem ipsum dolores amet
foo bar
Run Code Online (Sandbox Code Playgroud)
Pek*_*ica 22
我不认为你可以在纯CSS中做到这一点.
您必须在最后两个单词之间放置一个不间断的空格:
foo bar
Run Code Online (Sandbox Code Playgroud)
或者将最后两个单词放入span:
<span style="white-space: nowrap">foo bar</span>
Run Code Online (Sandbox Code Playgroud)
我不认为仅靠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(" ");
// 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);
Run Code Online (Sandbox Code Playgroud)
刚刚写了这个无依赖的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 "):void 0)})}
Run Code Online (Sandbox Code Playgroud)
您可以通过执行此操作
objs = document.getElementsByClassName('corrected');
buddySystem(objs);
Run Code Online (Sandbox Code Playgroud)
现在,您将永远不会为corrected该类的任何标签一个字。
您也可以根据需要使用jQuery。
$(".corrected").buddySystem()
查看链接以了解所有可能性。