我想根据固定高度截断文本。截断文本时,使用“更多”链接扩展为文本。当文本被展开时,“较少”链接用于折叠文本。我把js写成这样:
$(document).ready(function () {
// line height in 'px'
var maxheight=218;
var showText = "More";
var hideText = "Less";
$('.textContainer_Truncate').each(function () {
var text = $(this);
if (text.height() > maxheight){
text.css({ 'overflow': 'hidden','height': maxheight + 'px' });
var link = $('<a href="#">' + showText + '</a>');
var linkDiv = $('<div></div>');
linkDiv.append(link);
$(this).after(linkDiv);
link.click(function (event) {
event.preventDefault();
if (text.css('height') == 'auto') {
$(this).html(showText);
text.css('height', maxheight + 'px');
} else {
$(this).html(hideText);
text.css('height', 'auto');
}
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
html代码是:
<div class="textContainer_Truncate">
<p>content</p>
</div>
Run Code Online (Sandbox Code Playgroud)
我的问题是“更多”链接有效,但“更少”链接无效。也就是说,当点击更多时,文本被展开,但当点击更少时它不会返回。这里有什么问题?谢谢
这只是一个小错误,这个:
if (text.css('height') == 'auto') {
Run Code Online (Sandbox Code Playgroud)
应该是这样的:
if (text.height() > maxheight) {
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14787 次 |
| 最近记录: |