我需要从溢出元素中删除最后一个单词,直到元素的内容不再溢出为止。 我试过这个
var pageHeight = 25.7; //This is cm, but I can convert to px easily enough
var pageContent = "";
var d = $("<div />").appendTo('body');
function removeLast(d){
//remove last word
var str = $(d).html()
var lastIndex = str.lastIndexOf(" ");
var str = str.substring(0, lastIndex);
$(d).html(str);
if ($(d).height() > pageHeight){
removeLast(d); //to try and loop around
}
}
这个
$(d).html( trimSentence($(d).html()) );
if ($(d).height() > pageHeight){
removeLast(d);
}
(以下来自另一个SO答案&amp;似乎工作正常)
function trimSentence(string){
var found = false;
var index = null;
var characterGroups = string.split(' ').reverse();
var position = 1,//skip the first one since we know that's the end anyway
elements = characterGroups.length,
element = null,
prevHadUpper = false,
last = null,
lookFor = '';
while(!found && position < elements) {
element = characterGroups[position].split('');
if(element.length > 0) {
last = element[element.length-1];
// test last character rule
if(
last=='.' || // ends in '.'
last=='!' || // ends in '!'
last=='?' || // ends in '?'
(last=='"' && prevHadUpper) // ends in '"' and previous started [A-Z]
) {
found = true;
index = position-1;
lookFor = last+' '+characterGroups[position-1];
} else {
if(element[0] == element[0].toUpperCase()) {
prevHadUpper = true;
} else {
prevHadUpper = false;
}
}
} else {
prevHadUpper = false;
}
position++;
}
var trimPosition = string.lastIndexOf(lookFor)+1;
return string.substr(0,trimPosition);
}
但是当循环使用时,两者似乎都不起作用,但在没有循环的情况下工作正常。 我试图让div的内容减少,直到没有溢出,并且溢出&#39;应该将文本复制到另一个字符串中(但这可能是另一个问题)
答案 0 :(得分:0)
使用text()方法代替html():
var str = $(d).text()
html()包含html标记,但text()方法仅包含文本字符串。
答案 1 :(得分:0)
我建议使用CSS
规则
word-wrap
来自docs
The word-wrap CSS property is used to specify whether or not the browser
may break lines within words in order to prevent overflow
when an otherwise unbreakable string is too long to fit in its containing box.