jQueryで文字列末尾省略 + ...表示
jQueryで文字列末尾省略 + ...表示
jQuery 例
このサイトにお世話になった。
書き方としては、これが簡単だった。
今回は、・・・の部分にカーソルを合わせると省略した部分が出るようにしたかった。
以前使った、tooltipsterこれを利用。
afterTxt…の部分を<span class="sss">...</span>
みたいな感じにしてclassにクリックイベントを付けた。
$(function(){
var $setElm = $('ul li');
var cutFigure = '30'; // カットする文字数
var afterTxt = ' …'; // 文字カット後に表示するテキスト
$setElm.each(function(){
var textLength = $(this).text().length;
var textTrim = $(this).text().substr(0,(cutFigure))
if(cutFigure < textLength) {
$(this).html(textTrim + afterTxt).css({visibility:'visible'});
} else if(cutFigure >= textLength) {
$(this).css({visibility:'visible'});
}
});
何回も繰り返して書くと、上記の四角で囲まれた部分が1回で終わらせたいなと思う。
そこで、call関数を使って
$setElm.each(function(){
aaa.call(this.cutFigure);
}
中の部分は関数にする
function aaa(cutFigure){
var textLength = $(this).text().length;
var textTrim = $(this).text().substr(0,(cutFigure))
var afterTxt = '...';
if(cutFigure < textLength) {
$(this).html(textTrim + afterTxt).css({visibility:'visible'});
} else if(cutFigure >= textLength) {
$(this).css({visibility:'visible'});
これで、マウスオーバーするとツールチップが表示される。