【问题标题】:How to set max length in text如何设置文本的最大长度
【发布时间】:2018-01-15 03:59:16
【问题描述】:

如何设置文本的最大长度并以... 结尾?

我已经尝试过substr,但它只是剪切了第一个和最后一个文本。

我想要的是,例如我有一个divwidth: 500pxheight: 500px

当文字超过高度时,文字会以...剪切。

我想要这样

我试过这样,但是当超出宽度而不是高度时,文本会被剪切。

我使用了以下 css

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

【问题讨论】:

    标签: php html css


    【解决方案1】:

    Javascript方式

    查看这个答案smart way to shorten long strings with javascript

    PHP方式

    我在向浏览器发送文本之前使用这个 php 辅助函数:

    function readMoreHelper($story_desc, $chars = 100) {
      if (strlen($story_desc) <= $chars)
        return $story_desc;
      $story_desc = substr($story_desc,0,$chars);
      $story_desc = substr($story_desc,0,strrpos($story_desc,' '));
      $story_desc = $story_desc." ...";
      return $story_desc;
    }
    

    因此,在您的处理程序中,您可以按如下方式传递您的文本

    readMoreHelper($yourLongText, 200)
    

    【讨论】:

      【解决方案2】:

      使用 CSS,您可以使用:

      -webkit-line-clamp: 3; //number line allow
      -webkit-box-orient: vertical;
      display: -webkit-box;
      overflow: hidden;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-04-05
        • 1970-01-01
        • 2012-04-27
        • 1970-01-01
        • 2018-08-31
        • 1970-01-01
        • 2014-06-19
        相关资源
        最近更新 更多