(HTML) 假设我有固定宽度的容器。其中一些标题将超过一行。我想隔离这些线并对每条线做不同的事情。有没有一种方法可以使用 JavaScript 来计算标题到下一行的位置,例如在每行周围放置一个跨度?
最佳答案
Hacky and dirty:在同一个容器中逐个字符地呈现相同的字符串,直到它不适合为止,然后获取该字符串并将其包装在 <span>
中。 , 重复。
$(function(){
$h = $('.fixed').find('h3');
$h.each(function(i,e){
var txt = $(e).text();
$th = $('<h3 />').prependTo($(e).parent());
var lh = $(e).text('X').height();
$(e).text('');
while (txt.length > 0) {
$th.text($th.text() + txt[0]);
txt = txt.slice(1);
if (($th.height() > lh) || (txt.length <= 0)) {
var shc = $th.text().split(' ');
var ph = shc.slice(0,-1).join(' ')+' ';
if (txt.length <= 0) { ph += shc.pop(); }
$('<span />').text(ph).appendTo($(e));
$th.text(shc.pop());
}
}
$th.remove();
})
});
使用上有一些限制。例如,标题不应包含纯文本以外的任何内容 - 任何 HTML 标签都将被剥离。
当然还有fiddle为此。
关于javascript - 使用 Javascript/jQuery 确定标题在何处中断到下一行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3960336/