在p标签的宽度内切片文本

时间:2013-09-27 07:56:54

标签: javascript jquery html css

我有p tag with fix width。如果一个长句话出现,那么该句子应该自动切片,如下图所示。

enter image description here

所以这句话应该是这样的。

enter image description here

我尝试了许多Css选项,例如word-wrap and text-overflow,但没有任何效果。有些会使宽度增加,有些则会产生其他问题。我也试过了overflow:hidden,这隐藏了第二行,但没有在第一行末尾添加...

2 个答案:

答案 0 :(得分:8)

使用:

p {
    text-overflow: ellipsis;
    display block;
    width: 100px;
    overflow: hidden;     
    white-space: nowrap;
    padding: 5px;
    border: solid 1px #000;
}

实施例: http://jsfiddle.net/ezywm/2/

答案 1 :(得分:0)

检查此前一个stackoverflow问题以获取此答案 Insert ellipsis (...) into HTML tag if content too wide

我们也可以在jQuery的帮助下实现这个效果。

查看dotdotdot jQuery插件。

<强> CSS3:

    <!DOCTYPE HTML>
    <html>
    <head>
    <meta charset="utf-8">
    <title>ellipsis</title>
    </head>
    <style type="text/css">
   p {
        border: 1px solid #CCCCCC;
        overflow: hidden;
        padding: 2px;
        text-overflow: ellipsis;
        white-space: nowrap;
        width: 250px;
       } 
    </style>
    <body>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry.</p>
    </body>
    </html>