使用Javascript/jQuery确定标题在下一行的位置吗? [英] Use Javascript/jQuery to determine where a heading breaks to the next line?
问题描述
(HTML)假设我有固定宽度的容器.其中一些标题将超过一行.我想隔离这些行,并在每行中分别做一些事情.使用JavaScript,有没有一种方法可以计算出标题下一行的位置,例如在每行周围放置一个跨度?
(HTML) Let's say I have within fixed-width containers. Some of these headings will be longer than one line. I would like isolate these lines and do separate things to each line. Is there a way, with JavaScript, to calculate where the heading has broken to the next line and to for example put a span around each line?
推荐答案
又脏又乱:在同一容器中逐字符显示相同的字符串,直到不适合为止,然后将该字符串包装在一个字符串中<span>
,重复.
Hacky and dirty: render the same string in the same container char-by-char until it doesn't fit, then take this string and wrap it in a <span>
, repeat.
$(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标签都将被剥离.
There are some limitations in usage. For example, headings aren't expected to contain anything but plain text - any HTML tags will be stripped off.
当然还有小提琴.
这篇关于使用Javascript/jQuery确定标题在下一行的位置吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!