如何创建缩短文本

How to create shorten text?

本文关键字:文本 创建 何创建      更新时间:2023-09-26

我有像这样的 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

将以下样式添加到.box

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

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

您需要设置文本溢出:省略号用于此目的,请参阅此链接以获取更多信息

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

试试这个:-

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

试试这个,

 .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/

试试这个:

$(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);
        }
    });
});