【发布时间】:2012-06-07 20:07:28
【问题描述】:
使用 zepto.js,如何从 ul 中显示 X 项,隐藏其余项并显示它们 仅当用户单击“显示更多”链接/按钮时?
10 倍!
【问题讨论】:
标签: javascript html zepto
使用 zepto.js,如何从 ul 中显示 X 项,隐藏其余项并显示它们 仅当用户单击“显示更多”链接/按钮时?
10 倍!
【问题讨论】:
标签: javascript html zepto
基本上有两种方式。
使用 zepto 切换类并使用 css 定义要隐藏的内容
/* show only the first 3 list items */
ul.collapsed li:nth-child(n+4) {
display: none;
}
var $list = $(ul.collapsed); // initially the list is collapsed
// use a show-more link to toggle display of remaining items
$("a.show-more").click(function(){
// get the current state of the list by querying the className
var shouldShow = $list.hasClass("collapsed") == true;
$list.toggleClass("collapsed");
// set the link text according to the task (show or hide)
$(this).html(shouldShow ? "Show less" : "Show more");
// its a link, don't follow it
return false;
});
使用 zepto “独立”
var $list = $(ul);
// use the link to set the css properties directly
$("a.show-more").click(function(){
var shouldShow = $list.hasClass("collapsed") == true;
$("li:nth-child(n+4)", $list).css({
"display": shouldShow : "" : "none"
});
$(this).html(shouldShow ? "Show less" : "Show more");
return false;
});
【讨论】:
这是完成您的要求的一种方法。
$(function() {
$('li').slice(5).toggle();
$('span').click(function() {
$('li').slice(5).toggle();
});
});
第一个 .slice(5).toggle() 函数获取所有选定的列表项,将它们缩小到从索引 5 开始到末尾的元素子集。然后它切换它在该子集中找到的第一个元素的可见状态。
然后我们将一个函数附加到 span 上的 click 事件,这是我们的 Show/Hide 元素。该函数实际上与我们运行以隐藏索引 5 之后的所有元素的初始函数相同。
查看此JS Fiddle 以获取工作示例。另外,为了进一步参考这里是the docs on .slice(),这里是the docs on .toggle()。
希望有帮助!
【讨论】: