如何创建“显示更多”按钮并指定最初显示的文本行数
我正在寻找一种方法来在我的响应式网站上创建一个幻灯片“显示更多”function,该function会在两个段落之后切断。
我之前使用静态网站实现了这一点,通过对容器应用设置高度并使用overflow: hidden
,然后设置容器高度的动画。
但是响应时,容器会以不同的浏览器宽度压缩文本,因此文本可能占用更多/更少的空间。 此外,每次推送时,段落上方可能会有不同的内容。 因此设置height
可能不会完全覆盖两条线。
如果你需要演示,请查看这个jsFiddle: http : //jsfiddle.net/XVAzU/ 。
所以我需要在段落的两行之后切断,无论容器的宽度是多少,或者在该段落之前或之后。
谢谢你的期待!
从你的小提琴开始,将内容包装到一个带有默认content
类的
中,用于选择和一个名为hideContent
的类,当点击show more/show less
链接时,它将与showContent
交换。
我还删除了文本所在的
。文本现在在content-div中,我们现在也可以应用正确的高度和行高设置。
HTML:
CSS:
.hideContent { overflow: hidden; line-height: 1em; height: 2em; } .showContent { line-height: 1em; height: auto; }
我假设设置line-height
将确保它在所有浏览器中都是相同的。 尽管如此,我并不是100%肯定。
我将click事件附加到“show more”链接,该链接使用jQueryUI switchClass()切换div上的类:
$(".show-more a").on("click", function() { var $this = $(this); var $content = $this.parent().prev("div.content"); var linkText = $this.text().toUpperCase(); if(linkText === "SHOW MORE"){ linkText = "Show less"; $content.switchClass("hideContent", "showContent", 400); } else { linkText = "Show more"; $content.switchClass("showContent", "hideContent", 400); }; $this.text(linkText); });
JsFiddle演示 – 显示更多/显示更少并应用行高和动画
$(".show-more a").on("click", function() { var $this = $(this); var $content = $this.parent().prev("div.content"); var linkText = $this.text().toUpperCase(); if (linkText === "SHOW MORE") { linkText = "Show less"; $content.switchClass("hideContent", "showContent", 400); } else { linkText = "Show more"; $content.switchClass("showContent", "hideContent", 400); }; $this.text(linkText); });
div.text-container { margin: 0 auto; width: 75%; } .hideContent { overflow: hidden; line-height: 1em; height: 2em; } .showContent { line-height: 1em; height: auto; } .showContent { height: auto; } h1 { font-size: 24px; } p { padding: 10px 0; } .show-more { padding: 10px 0; text-align: center; }
如果您正在搜索仅限css的解决方案,请查看以下内容:
HTML
// CSS
.show-hide-text { display: flex; flex-wrap: wrap; } .show-hide-text a { order: 2; } .show-hide-text p { position: relative; overflow: hidden; max-height: 60px; // The Height of 3 rows } .show-hide-text p { display: -webkit-box; -webkit-line-clamp: 3; // 3 Rows of text -webkit-box-orient: vertical; } .show-less { display: none; } .show-less:target { display: block; } .show-less:target ~ p { display: block; max-height: 100%; } .show-less:target + a { display: none; }
例如: https : //codepen.io/srekoble/pen/WGBzZa?edit = 1100