我有一个 div,它包含一个动态填充的段落。有时段落是20行,有时是3行。
我想设置一个高度限制,如果 div 大于此高度(由于段落中有更多行),它将缩小到只显示 3 行文本,然后有一个“查看更多”按钮将根据请求展开和/或折叠 div 以显示段落中的剩余行。
<div class="hero-unit">
<h1>Product Description</h1>
<p>{{paragraph}}</p>
</div>
关于如何尽可能轻松地完成此操作的任何提示?
最佳答案
如果您只需要 3 行,请注意这意味着高度应为 3*line-height
。然后你可以这样做:
HTML
<div class="hero-unit">
<h1>Product Description</h1>
<p>...</p>
<a>More</a>
</div>
CSS
p {
line-height: 18px;
height: 54px;
overflow: hidden;
}
overflow: hidden
将隐藏超出容器边界的内容。
jQuery
然后我们切换高度限制。
$('a').click(function() {
var p = $('a').prev('p')
var lineheight = parseInt(p.css('line-height'))
if (parseInt(p.css('height')) == lineheight*3) {
p.css('height','auto');
$(this).text('Less')
} else {
p.css('height',lineheight*3+'px');
$(this).text('More')
}
});
参见 demo .
关于html - 使 DIV 可扩展,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14969933/