LoginSignup
21
25

More than 5 years have passed since last update.

意外と需要がある(泣)文字数を省略して「...」にしたい。複数行のとき!

Last updated at Posted at 2017-10-25

意外と需要がある。。忘れた頃にやってくるこの仕様 :confounded:

1行のときはtext-overflowプロパティを使用すれば問題ありません!

問題は複数行の時。

解決方法(jQuery)

高さを指定して高さを超えたら(改行されたら)「…」に書き換える。

// ▼文字列を省略して「…」を付与
jQuery(function($) {
  $('.js-text-overflow').each(function() {
    var $target = $(this);
    // オリジナルの文章を取得する
    var html = $target.html();
    // 対象の要素を、高さにautoを指定し非表示で複製する
    var $clone = $target.clone();
    $clone
      .css({
        display: 'none',
        position : 'absolute',
        overflow : 'visible'
      })
      .width($target.width())
      .height('auto');
    // DOMを一旦追加
    $target.after($clone);
    // 指定した高さになるまで、1文字ずつ消去していく
    while((html.length > 0) && ($clone.height() > $target.height())) {
      html = html.substr(0, html.length - 1);
      $clone.html(html + '...');
    }
    // 文章を入れ替えて、複製した要素を削除する
    $target.html($clone.html());
    $clone.remove();
  });
});

解決方法(css)

横幅は任意で設定。
overflow: hidden;

height: 50px;
がキモ。(50px)は任意でOK

.js-text-overflow {
  overflow: hidden; /* overflow: hidden; がキモ。*/
  width: 245px;
  height: 50px;
  font-size: 16px;
}

解決方法(html)

Classを指定してあげるとOK:v:

<p class="js-text-overflow">
 2行以上は3点リーダー2行以上は3点リーダー2行以上は3点リーダー2行以上は3点リーダー2行以上は3点リーダー
</p>

参考サイト
:writing_hand: Developers.IO: 文字列を省略して「…」を付与する方法 – CSS/jQuery

21
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
21
25