当点击导航菜单链接时用javascript对div进行折叠/展开
问题描述:
当前,下面的代码在用户每次点击菜单项时展开DIV(如果他在同一链接上点击几次,它会折叠并展开相同的数字的时代,但它从来没有保持折叠/关闭)。当点击导航菜单链接时用javascript对div进行折叠/展开
我想那是什么,当用户点击同一个菜单项链路上的第二次,DIV被折叠,并保持这个样子。像这样的网站上
编辑:我实现上述可能不是很清楚,所以总结:
当前进程:打开导航菜单链接
- 一次点击(展开)相关的 DIV
- 再次点击相同的导航链接隐藏(折叠)DIV 然后自动重新打开它
所需的新工艺:导航菜单链接
- 一个键打开(展开)相关 DIV
- 在相同的导航链接隐藏(倍)的DIV 再点击一下鼠标就是这样。 DIV保持折叠状态,直到用户再次点击相同的链接或其他菜单项。
我怎么能做到这一点?非常感谢
见http://jsfiddle.net/u3qtt6fo/5/
JS:
$("a").click(function() {
var page = $(this).data("page");
var active = $(".fold.active");
// if there is visible fold element on page (user already clicked at least once on link)
if(active.length) {
$(".fold.active")
.animate({ width: "0" }, 200)
.animate({ height: "0" }, 200, function() {
// this happens after above animations are complete
$(this).removeClass("active")
$("#"+page)
.addClass("active")
.animate({ height: "500px" }, 1000, 'linear')
.animate({ width: "500px" }, 400,'linear')
})
// clicking for the first time
} else {
$("#"+page)
.addClass("active")
.animate({ height: "500px" }, 1000,'linear')
.animate({ width: "500px" }, 400,'linear')
}
});
HTML
<div id="fold1" class="fold">Div menu item 1</div>
<div id="fold2" class="fold">Div menu item 2</div>
<div id="fold3" class="fold">Div menu item 3</div>
<div id="fold4" class="fold">Div menu item 4</div>
<nav>
<ul>
<li><a href="#" data-page="fold1">Menu item 1</a></li>
<li><a href="#" data-page="fold2">Menu item 2</a></li>
<li><a href="#" data-page="fold3">Menu item 3</a></li>
<li><a href="#" data-page="fold4">Menu item 4</a></li>
</ul>
</nav>
CSS:
.fold {
display: none;
width: 0;
height: 0;
}
.fold.active {
display: inline-block;
}
#fold1 {
border: solid 5px #bada55;
background: red;
}
#fold2 {
border: solid 5px #fed900;
background: aqua;
}
#fold3 {
border: solid 5px #223322;
background: green;
}
#fold4 {
border: solid 5px #55bada;
background: purple;
}
ul {
position: absolute;
top: 50px;
right: 50px;
list-style-type: none;
}
答
这是你需要什么? http://jsfiddle.net/u3qtt6fo/11/
我编辑你的代码一点点,我加了jQuery选择“动画”
$("a").click(function() {
var page = $(this).data("page");
if ($('div:animated').id != page) {
var active = $(".fold.active");
// if there is visible fold element on page (user already clicked at least once on link)
if (active.length) {
active.animate({
width: "0"
}, 200)
.animate({
height: "0"
}, 200, function() {
// this happens after above animations are complete
$(this).removeClass("active");
})
// clicking for the first time
} else {
$("#" + page)
.addClass("active")
.animate({
height: "500px"
}, 1000, 'linear')
.animate({
width: "500px"
}, 400, 'linear')
}
}
});
谢谢您的回答。几乎。但是,当用户在菜单项上单击几次时,您的代码会自动展开DIV折叠。我想要的是,如果他点击1x然后DIV展开(=可见),并且如果他再次点击1x DIV折叠并保持折叠(通过折叠,我的意思是封闭/不可见)。多谢了 – Greg 2014-12-04 21:33:26
试试这个http://jsfiddle.net/rnjea41y/我把“else”子句改成了“if”,它检查是否点击了新链接,新的div将被显示。另外,我在.fold的CSS中添加了“position:absolute” – lmazgon 2014-12-04 23:24:52
谢谢Imazgon,这正是我所需要的。非常感谢! – Greg 2014-12-05 16:09:31