截断段前100个字符并隐藏段落的其余内容以显示/隐藏更多/更少链接的rest符号

我有超过500个字符的段落。 我想只得到最初的100个字符并隐藏它的其余部分。 另外我想在100个字符旁边插入“更多”链接。 点击更多链接整个段落应显示并编辑文本“更多”到“更少”,点击“更少”它应切换行为。 段落是动态生成的我不能使用.wrap()包装它的内容。 这是我拥有的和我想要的例子。

这就是我所拥有的:

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text.

这是DOM加载时我想要的

  

It is a long established fact that a reader will be distracted by ..More

当用户点击“更多”时,这就是我想要的

  

It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text. ..Less

当我们点击“Less”时,它应该还原点击“更多”的内容。

我正在使用jQuery来分割,切片和将子字符串包装到我要隐藏的span中,但这不起作用。

 var title = $("p").text(); var shortText = jQuery.trim(title).substring(100, 1000).split(" ") .slice(0, -1).join(" ") + "...More >>"; shortText.wrap(''); 

小提琴: http : //jsfiddle.net/iambriansreed/bjdSF/

jQuery的:

 jQuery(function(){ var minimized_elements = $('p.minimize'); var minimize_character_count = 100; minimized_elements.each(function(){ var t = $(this).text(); if(t.length < minimize_character_count ) return; $(this).html( t.slice(0,minimize_character_count )+'... More'+ ''+ t.slice(minimize_character_count ,t.length)+' Less' ); }); $('a.more', minimized_elements).click(function(event){ event.preventDefault(); $(this).hide().prev().hide(); $(this).next().show(); }); $('a.less', minimized_elements).click(function(event){ event.preventDefault(); $(this).parent().hide().prev().show().prev().show(); }); });​ 

这不是谷歌的顶级结果,但我使用了jQuery Expander插件取得了巨大的成功。 这很好,因为它不会隐藏搜索引擎机器人的任何内容。

感谢@iambriansreed的好function,这里有一个略微的修改来截断段落中的段落

   

看起来有几个人打败了我,但这就是我想出来的。

 var MORE = "... More...", LESS = " Less..."; $(function(){ $("p").each(function(){ var $ths = $(this), txt = $ths.text(); //Clear the text $ths.text(""); //First 100 chars $ths.append($("").text(txt.substr(0,100))); //The rest $ths.append($("").text(txt.substr(100, txt.length)).hide()); //More link $ths.append( $("").text(MORE).click(function(){ var $ths = $(this); if($ths.text() == MORE){ $ths.prev().show(); $ths.text(LESS); } else{ $ths.prev().hide(); $ths.text(MORE); } }) ); }); }); 

你看过jQuery Truncator插件了吗?

它几乎完全符合你的描述。

对于每个来这里寻找更多节目的人来说……这是另一个插件http://viralpatel.net/blogs/dynamically-shortened-text-show-more-link-jquery/