如何创建缩短文本?

时间:2013-11-11 10:51:22

标签: javascript jquery html css

我喜欢HTML:

<div class="box">
   <a href="#">Stackoverflow is very useful site and I love it</a>
</div>

和CSS一样:

.box {
    width:230px;
    height:50px;
    line-height:50px;
    background:#eee;
}

.box a {
    color:#000;
}

我想创建简短的链接文本。如果它本身溢出box类,则将其取为“...”。我怎么能用css或jquery做到这一点?

检查jsfiddle here

6 个答案:

答案 0 :(得分:6)

将以下样式添加到.box

text-overflow: ellipsis;
white-space: nowrap;
overflow: hidden;

工作样本:http://jsfiddle.net/qLzK7/

答案 1 :(得分:3)

您需要为此目的设置文本溢出:省略号see this link for more info

答案 2 :(得分:3)

.box a 
{
    color:#000;
    text-overflow: ellipsis;
}

答案 3 :(得分:2)

试试这个: -

.box{
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}

答案 4 :(得分:1)

试试这个,

 .box{
width:230px; 
height:50px;
line-height:50px
;background:#eee; 
overflow:hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.box a{color:#000}

http://jsfiddle.net/9yatw/

答案 5 :(得分:1)

试试这个:

$(document).ready(function() {
    var showChar = 37;
    var ellipsestext = "...";
    $('.box').each(function() {
        var content = $(this).find("a").html();
        if(content.length > showChar) {
         var a = content.substr(0, showChar);
         var b = content.substr(showChar-1, content.length - showChar);
         var html = a + ' ' + ellipsestext;
            $(this).find("a").html(html);
        }

    });
});