代码:
标记:
<div class="test">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta. Mauris massa. Vestibulum lacinia arcu eget nulla. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </div>
<div class="results">
</div>
JavaScript与jQuery:
var text = $('div.test').text();
var words = text.split(' ');
var html = '';
$.each(words, function(i, word) {
html += '<span>' + word + '</span> ';
});
$('div.test').html(html);
var farthestRight = 0;
$('div.test span').each(function(i,e) {
var left = $(e).position().left;
var width = $(e).width();
if (left + width > farthestRight) {
farthestRight = left + width;
}
// Uncomment to see debug data
// $('.results').append('<div>' + left + ', ' + width + ', ' + (left + width) + '</div>');
});
$('.results').append('<div>' + farthestRight + '</div>');
function getTextRect( containerNode ) {
// For simplicity, we assume plain text here
// (no nested markup)
var textRect,
textNode = containerNode.childNodes[0],
textRange = document.createRange();
textRange.selectNode( textNode );
textRect = textRange.getBoundingClientRect();
// Clean up
textRange.detach();
return textRect;
}
// You can read the width with getTextRect( someNode ).width
span
,逐个单词填充文本,并每次检查宽度是否实际增加。一旦不再增加,就必须发生换行,因此只需将先前的宽度与完整宽度进行比较即可。<div>This is a long text that wraps somewhere, but we don't know where exactly...
</div>
<h2 id="result"></h2>
var text = $('div').text();
$('div').empty().append($('<span>'));
var words = text.split(' ');
var lastWidth = 0;
for (var word in words) {
if (words[word] == '') continue;
var newWidth = $('div span').append(words[word] + ' ').width();
if (!(newWidth > lastWidth)) {
$('#result').text($('div span').text(text).width()).append('px');
break;
}
lastWidth = newWidth;
}
$('div').text(text);
{{链接1:JSFiddle}}
$('#result').text($('div').text(text).width()-lastWidth).append('px');
更改为$('#result').text($('div span').text(text).width()).append('px');
,因为您之前是检查包含元素的宽度,然后从中减去上次测量的 span 宽度,这并没有给出正确的换行长度。 - Reed