我正在尝试在某些包装文本上设置下划线,该文本适合文本底行的宽度,同时仅出现在该底线下方。图1说明了所需的效果
图1
使用此HTML:
<h2><span class="inline-block">optatur, volendit inum simolor</span></h2>
并将span
设置为display:inline;
我可以使下划线与文字的宽度完全吻合,但它会突出显示所有文字。
或,将span
设置为display:inline-block;
我可以将下划线仅显示在底线下,但它会填充父级的整个宽度。
请参阅此JSfiddle以获取上述示例:http://jsfiddle.net/PWDV7/1/
有没有办法达到图1的结果?
答案 0 :(得分:1)
从this answer到关于找到换行的问题,我设法提出了这个解决方案(简而言之,它涉及使用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/
答案 1 :(得分:0)
更改代码如下:
<强> HTML 强>
<h2>optatur, volendit <span>inum simolor</span></h2>
<强> CSS 强>
h2 {
width:200px;
text-align:center;
}
h2 span {
border-bottom:3px solid black;
width:100%;
}
我改变的只是<span>
的位置来包装你想要边框的文字。
<强> JsFiddle 强>