19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

jQueryで表示文字数制限

Posted at

表示文字数を制限して、デフォルトでは「ほげほげ…[全文表示]」のように表示しておいて、[全文表示]をクリックしたら全文表示されるよくあるやつです。

$(window).on('load', function(){
  if($('.textOverFlow').length > 0){
    var count = 100; // デフォルトで表示する文字数
    $('.textOverFlow').each(function(){
      var target = $(this),
          fullTxt = target.text();
      if(fullTxt.length > count){
        target.text(fullTxt.substr(0,count) + '');
        var moreLead = $('<span class="moreLead">[全文表示]</span>');
        target.append(moreLead);
        moreLead.on('click', function(){
          target.text(fullTxt);
          $(this).remove();
        });
      }
    });
  }
});


<p class="textOverFlow">テキストテキスト</p>
,moreLead {
 color: blue;
 cursor: pointer;
}
19
19
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
19
19

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?