我有一些关于我试图添加到我的 jQuery 的功能的问题,以启用按钮或文本以在单击时扩展/收缩所有 div... 我想弄清楚如何在打开时保持第一个 div页面加载。
这是jQuery:
(document).ready(function(){
//Hides containers on load
$(".toggle_container").hide();
//Switch "Open" and "Close" state on click
$("h2.trigger").toggle(function(){
$(this).addClass("active");
}, function () {
$(this).removeClass("active");
});
//Slide up and down on click
$("h2.trigger").click(function(){
$(this).next(".toggle_container").slideToggle("slow");
});
});
Run Code Online (Sandbox Code Playgroud)
和CSS:
// uses a background image with an on (+) and off (-) state stacked on top of each other
h2.trigger { background: url(buttonBG.gif) no-repeat;height: 46px;line-height: 46px;width: 300px;font-size: 2em;font-weight: normal;}
h2.trigger a {color: #fff;text-decoration: none; display: block;}
h2.active {background-position: left bottom;}
.toggle_container { overflow: hidden; }
.toggle_container .block {padding: 20px;}
Run Code Online (Sandbox Code Playgroud)
和 html
<h2 class="trigger"><a href="#">Heading</a></h2>
<div class="toggle_container">
<div class="block">Stuff goes here</div>
</div>
<h2 class="trigger"><a href="#">Heading 2</a></h2>
<div class="toggle_container">
<div class="block">Stuff goes here</div>
</div>
Run Code Online (Sandbox Code Playgroud)
所以它工作得很好,看起来很棒。但是,当我尝试让它保持第一个实例打开时,应该调整的背景图像显示 (-) 状态不会改变。我习惯的代码是:
$(".toggle_container:first").show();
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,有没有人知道一种更简单的方法来将第一个实例显示为打开,而不必为第一个项目创建特殊规则/类?另外,关于如何打开所有/关闭所有链接的任何想法?
谢谢!
您可以将所有 jQuery 更改为:
$(".toggle_container:not(:first)").hide();
$("h2.trigger:first").addClass("active");
$("h2.trigger").click(function(){
$(this).toggleClass("active");
$(this).next(".toggle_container").slideToggle("slow");
});
Run Code Online (Sandbox Code Playgroud)
这隐藏了除第一个之外的所有内容.toggle_container,将 应用于class="active"它的匹配<h2>,并且toggle()更简单,现在单击切换类...所以我们可以添加active匹配它在页面加载时打开,它会正确运行。
此外,打开/关闭所有看起来像这样:
<a href="#" id="openCloseAll">Open All</a>
Run Code Online (Sandbox Code Playgroud)
像这样的jQuery:
$("#openCloseAll").toggle(function() {
$(this).text("Close All");
$(".toggle_container:hidden").prev(".trigger").click();
}, function() {
$(this).text("Open All");
$(".toggle_container:visible").prev(".trigger").click();
});
Run Code Online (Sandbox Code Playgroud)
这会在第一次点击时打开所有关闭,更改其文本以准确描述下一次点击将执行的操作,并在下次点击时关闭所有打开,然后切换回来,冲洗,重复。