javascript 使用 jQuery 展开/折叠文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11408311/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
use jQuery to expand/collapse text
提问by Yujun Wu
I want to cut off text based on a fixed height.When the text is cut off, a "more" link is used to expand to text. When the text is expanded, a "less" link is used to collapse the text. I wrote the js as this:
我想根据固定高度截断文本。当文本被截断时,使用“更多”链接扩展为文本。当文本被展开时,“较少”链接用于折叠文本。我把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');
}
});
}
});
});
The html code is:
html代码是:
<div class="textContainer_Truncate">
<p>content</p>
</div>
My problem is that the "more" link works but the "less" doesn't. That is, when more is clicked, the text is expanded but it won't go back when the less is clicked.What's wrong here? Thanks
我的问题是“更多”链接有效,但“更少”链接无效。也就是说,当点击更多时,文本被扩展,但当点击更少时它不会返回。这里有什么问题?谢谢
采纳答案by adeneo
回答by Rafee
I believe you are looking this one
我相信你正在看这个
$(".act").click(function() {
var val = $(this).text();
if (val == "More") {
$("div").css('height', '200px');
$(this).text("less");
} else {
$("div").css('height', '20');
$(this).text("More");
}
return false;
});
div {
background-color: #CCA;
height: 20px;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<a href="" class="act">More</a>
<div>This fskdljfl sflsdajfsadf
<br />fsdafsdfsadfsdf dfjsadf slfkjsf</div>
above is the live example..
以上是活生生的例子..