如何使用 jQuery 实现“阅读更多”链接
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3553308/
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
How to implement a "read more" link with jQuery
提问by tchaymore
I want to be able to display a shortened version of a long text field by default, but then have a "read more" link that would expand the field to its full version. I have a pretty simple setup right now, but feel like there should be a more efficient way of doing this.
我希望能够在默认情况下显示一个长文本字段的缩短版本,但随后有一个“阅读更多”链接可以将该字段扩展到其完整版本。我现在有一个非常简单的设置,但觉得应该有一种更有效的方法来做到这一点。
Here's my current code:
这是我当前的代码:
$(document).ready(function () {
$("#narrative-full").hide();
$("a#show-narrative").click(function() {
$("#narrative-short").hide();
$("#narrative-full").show('fast');
});
$("a#hide-narrative").click(function() {
$("#narrative-full").hide();
$("#narrative-short").show('fast');
});
});
This works, but seems clunky. For example, it would be nice to have the original text not flicker or disappear briefly, but instead just smoothly expand. Any suggestions?
这有效,但看起来很笨重。例如,最好不要让原始文本短暂闪烁或消失,而只是平滑地展开。有什么建议?
回答by Stefan Kendall
There's a plugin for that.Don't reinvent the wheel.
有一个插件。不要重新发明轮子。
回答by rebelliard
From jQuery Recipes:
来自jQuery 食谱:
<html>
<head>
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$(".message").hide();
$("span.readmore").click(function(){
$(".message").show("slow");
$(this).hide();
});
});
</script>
</head>
<body>
<div>
Styles make the formatting job much easier and more efficient.
</div>
<span class="readmore">Read More...</span>
<div class="message">
To give an attractive look to web sites, styles are heavily used.
JQuery is a powerful JavaScript library that allows us to add dynamic elements to our web
sites. Not only it is easy to learn, but it's easy to implement too. A person must have a
good knowledge of HTML and CSS and a bit of JavaScript. jQuery is an open source project
that provides a wide range of features with cross-platform compatibility.
</div>
</body>
</html>
回答by Sumith Harshan
Check these plugins.You can do this easily.
检查这些插件。你可以很容易地做到这一点。
回答by Muffun
You could place the text in a div and place the first part directly in and the rest in a span within the div
您可以将文本放在 div 中,然后将第一部分直接放在 div 中,其余部分放在 div 中的一个跨度中
<div>
first part of the text
<span id="expendable" style="display:none">
second part of the text
</span>
</div>
In Jquery you do something like this:
在 Jquery 中,您可以执行以下操作:
$("expendable").slideToggle("slow");
The Jquery ref is here.
Jquery ref 在这里。