【JQuery】文字数制限(指定サイズを超えると「…」を表示)
指定したボックスサイズを超えると「…」を表示してテキストを省略するjsをプラグイン化しました。
スクリプトコードの読み込み
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> <script src="js/character_limit_box.js"></script> <script> $(function() { $('p').characterLimitBox(); }); </script>
html
<p>ああああああああああいいいいいいいいいいううううううううううええええええええええ</p>
CSS
テキストが表示される領域に縦横サイズを指定する
p { margin: 0; padding: 10px; box-sizing: border-box; border: 1px solid #666; width: 200px; height: 50px; }
javascript(character_limit_box.js)
;(function($) { $.fn.characterLimitBox = function(){ $(this).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(); }); }; })(jQuery);
コメントを残す