这是一种无需在段落中添加任何标记的方法。
HTML:
<div id="content">
<p>content_here</p>
<p>content_here</p>
<p>content_here</p>
<p>content_here</p>
</div>
你会想要一些像这样的 CSS:
.dorsal { display: none; }
接下来,JavaScript:
$('#content').find('p').html( function(){ // for every paragraph in container
var exposer = '<a href="#" class="expose">More...</a>', // link to insert
content = $(this).html().split(''),
cutLength = 50, // choose the cutoff point
anterior = content.slice( 0,cutLength ).join(''),
dorsal = content.slice( cutLength ).join(''),
joined =
anterior
+ exposer
+ '<span class="dorsal">'
+ dorsal
+ '</span>'; // assemble the new contents
return joined;
})
.on('click','.expose',function(e){
e.preventDefault();
var $thisp = $(this).closest('p');
$('#content').find('p').not( $thisp ).hide(); // hide others
$thisp // for the enclosing paragraph
.find('.dorsal') // select the hidden piece
.show() // show it
.end() // back to the paragraph
.find('.expose') // find the "show more" link
.hide(); // hide it
});
您将需要在您的 $(document).ready() 处理程序中使用它。
正如其他人指出的那样,有很多插件可以做这种事情。不过,有时自己解决问题很有用。
重新折叠和显示原始段落留作练习。
这是一个例子:http://jsfiddle.net/redler/wAY8g/1/
更新以支持多个段落组,根据 Ibanez 的评论:
$('#content').find('div').prepend(function() {
var exposer = '<a href="#" class="expose">More...</a>',
rawcontent = $(this).text(),
cutLength = 100,
abstract = rawcontent.split('').slice(0, cutLength).join(''),
abbreviated = '<span class="abstract">' + abstract + exposer + '</span>';
return abbreviated;
}).end().on('click', '.expose', function(e) {
e.preventDefault();
var $thisgroup = $(this).closest('div');
$('#content').children('div').not($thisgroup).hide(); // hide others
$thisgroup
.find('p').show()
.parent()
.append('<a href="#" class="showall">Show all</a>')
.end()
.closest('div').find('.abstract').hide();
}).on('click', '.showall', function() {
$(this).remove();
$('#content').find('div').show().end()
.find('p:visible').hide().end()
.find('.abstract').show();
});
为此,我们现在从通过 css 隐藏的所有段落开始,脚本在加载时构建并显示摘要。还更新以提供重新显示原始状态的链接。
示例:http://jsfiddle.net/ZRB92/1/