我试图在一些换行文本上实现下划线,该下划线适合底行文本的宽度,同时仅出现在该底线下方。图1说明了期望的效果
Figure 1
使用这个 HTML:
<h2><span class="inline-block">optatur, volendit inum simolor</span></h2>
并设置span
to display:inline;
我可以让下划线与文本的宽度完美契合,但它会为所有文本添加下划线。
Or,设置span
to display:inline-block;
我可以让下划线仅出现在底线下方,但随后它会填充父级的整个宽度。
请参阅 JSfiddle 了解上述示例:http://jsfiddle.net/PWDV7/1/ http://jsfiddle.net/PWDV7/1/
有什么办法可以达到图1的效果吗?
凭借良好的腿从这个答案 https://stackoverflow.com/questions/3738490/finding-line-wraps/3744583#3744583对于有关查找换行的问题,我设法提出了这个解决方案(简而言之,它涉及使用 JS 来查找发生换行的位置,并将跨度包裹在最后一行的所有文本周围):
function underLineText () {
$underlined_text.each(function(){
var $this = $(this);
var text = $this.text();
var originalText = text;
var breakWords = new Array();
//split the words into individual strings
var words = text.split(' ');
//find the height of the first word
$this.text(words[0]);
var height = $this.height();
//if there is more than one word
if (words.length > 1) {
//loop through all the words
for(var i = 1; i < words.length; i++){
$this.text($this.text() + ' ' + words[i]);
//check if the current word has a different height from the previous word
//if this is true, we have witnessed a word wrap!
if($this.height() > height){
height = $this.height();
//add the first word after the wrap to a predefined array
breakWords.push(words[i]);
}
//on the last iteration on the loop...
if (i === words.length - 1) {
if (breakWords.length > 0) {
//select the last word of the breakWords array
//(this is to handle cases where there there are more than one line or word wraps)
var breakStartAt = breakWords[breakWords.length - 1];
//add a span before the last word
var withSpan = '<span>'+breakStartAt;
//replace the last occurrence of this word with the span wrapped version
//(this is to handle cases where there are more than one occurrences of the last word)
originalText = originalText.replaceLast(breakStartAt,withSpan);
//close the last line with a span
originalText += "</span>";
}
}
}
}
//if there are no word wraps, wrap the whole text in spans
else {
originalText = '<span>'+originalText+'</span>';
}
//replace the original text with the span-wrapped mod
$(this).html(originalText);
});
}
你可以在这里看到它的工作原理:http://jsfiddle.net/PWDV7/5/ http://jsfiddle.net/PWDV7/5/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)