在这里完成js新手,很抱歉,如果我问一个愚蠢的问题:)
我有一个切换几个div的导航,每个链接打开它自己的div,如下所示:
<div class="drawer" id="link1" style="display: none">First link content</div>
<div class="drawer" id="link2" style="display: none">Second link content</div>
<div class="drawer" id="link3" style="display: none">Third link content</div>
<nav>
<ul>
<li><a href="#" class="menu" data-item="#link1">Link 1</a></li>
<li><a href="#" class="menu" data-item="#link2">Link 2</a></li>
<li><a href="#" class="menu" data-item="#link3">Link 3</a></li>
<li><a href="#">External link</a></li>
</ul>
</nav>
运行它的代码:
$(document).ready(function () {
$('.menu').click(function () {
var $clicked = $(this)
$('.menu').each(function () {
var $menu = $(this);
if (!$menu.is($clicked)) {
$($menu.attr('data-item')).hide();
}
});
$($clicked.attr('data-item')).toggle();
});
});
效果很好,但不是简单的显示/消失,我希望在触发时对div进行上下滑动切换效果。
我知道有slideUp和slideDown效果,但就像我说的那样,我对这一切都很新,我无法让它发挥作用。
小提琴在http://jsfiddle.net/15kene5v/,如果有人可以提供帮助,那就太好了。
答案 0 :(得分:1)
使用slideUp
和slideToggle
代替hide
和toggle
。
$(document).ready(function() {
$('.menu').click(function() {
var $clicked = $(this)
$('.menu').each(function() {
var $menu = $(this);
if (!$menu.is($clicked)) {
// Use slideUp here
$($menu.attr('data-item')).slideUp('slow');
}
});
// Use sildeToggle here
$($clicked.attr('data-item')).slideToggle('slow');
});
});
nav ul {
margin: 0;
padding: 0;
background-color: #6DB4F3;
text-align: center;
}
nav ul li {
display: inline-block;
margin: 10px;
}
nav ul li a {
color: white;
text-decoration: none;
}
.drawer {
height: 100px;
background-color: darkorange;
color: white;
text-align: center;
position: relative;
}
.drawer:after {
content: 'close';
left: 0;
top: 0;
position: absolute;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.4.0/css/font-awesome.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div class="drawer" id="link1" style="display: none">First link content</div>
<div class="drawer" id="link2" style="display: none">Second link content</div>
<div class="drawer" id="link3" style="display: none">Third link content</div>
<nav>
<ul>
<li><a href="#" class="menu" data-item="#link1">Link 1</a>
</li>
<li><a href="#" class="menu" data-item="#link2">Link 2</a>
</li>
<li><a href="#" class="menu" data-item="#link3">Link 3</a>
</li>
<li><a href="#">External link</a>
</li>
</ul>
</nav>
<div style="display:block">Content that gets pushed down</div>