一种可能过于复杂的解决方案:
$('p').each(
function() {
var that = $(this);
that.attr('data-fullheight', that.height());
that.height(that.height() / 2);
that.closest('div').append('<a src="#" class="readmore">Read more</a>');
});
$('div').on('click', 'a.readmore', function(e) {
var p = $(this)
.closest('div')
.find('p[data-fullheight]'),
full = p.attr('data-fullheight');
p.animate({
'height' : full == p.height() ? full/2 : full
},200)
});
它假定以下 HTML(尽管div
id
不是必需的):
<div id="text">
<p>...text...</p>
</div>
<a href="http://jsfiddle.net/davidThomas/TEGF7/" rel="nofollow">JS Fiddle 演示。
只是因为我认为最后一个还不够复杂,所以我想我也会发布这个(纯 JavaScript!)解决方案:
var readmores = [];
function heights(el) {
if (!el) {
return false;
}
else {
var h = parseInt(window.getComputedStyle(el, null).height, 10),
moreLess = document.createElement('a'),
text = document.createTextNode('Read more'),
parent = el.parentNode;
readmores.push(moreLess);
moreLess.src = '#';
moreLess.className = 'readmore';
moreLess.appendChild(text);
parent.insertBefore(moreLess, el.nextSibling);
el.setAttribute('data-fullheight', h);
el.style.height = Math.floor(h / 2) + 'px';
}
}
function toggleHeight(el) {
if (!el) {
return false;
}
else {
var full = el.getAttribute('data-fullheight'),
curHeight = parseInt(el.style.height, 10);
el.style.height = full == curHeight ? Math.floor(full / 2) + 'px' : full + 'px';
}
}
function toggleText(el) {
if (!el) {
return false;
}
else {
var text = el.firstChild.nodeValue;
el.firstChild.nodeValue = text == 'Read more' ? 'Read less' : 'Read more';
}
}
var paras = document.getElementsByTagName('p');
for (var i = 0, len = paras.length; i < len; i++) {
var cur = paras[i];
heights(cur);
}
for (var i=0, len=readmores.length; i<len; i++){
readmores[i].onclick = function(){
toggleHeight(this.previousElementSibling);
toggleText(this);
}
}
<a href="http://jsfiddle.net/davidThomas/TEGF7/1/" rel="nofollow">JS Fiddle 演示。
这有效(在 Chrome 21 中),但绝对不允许 IE 需要对其进行一些修改。