大家晚上好,我正在使用jquery创建一个弹出菜单。这个菜单是用按钮打开的,当你点击屏幕上的任何地方时关闭,我的问题是,现在每次你点击屏幕时功能再次启动,如果我使用return false
菜单中的链接不起作用。
我怎样才能解决问题?
这是我的jquery代码:
$('#menu-button').click(function() {
$('#menu-button').css('left', '-130px');
$('#header').animate({'top': '0px'}, 700);
return false;
});
$(window).click(function(event) {
$('#header').animate({'top': '-100px'}, 700);
$('#menu-button').css({left: '5px'});
return false
});
这是html:
<nav id="header">
<a href="page1.html" title="">1</a></li>
<a href="page2.html" title="">2</a></li>
<a href="page3.html" title="">3</a></li>
</nav> <!-- header ends here -->
<a href="" id="menu-button">Menu</a>
这是css:
#header {
width: 100%;
height: 100px;
overflow: hidden;
position: fixed;
top: -100px;
left: 0;
background-color: blue;
z-index: 10;
}
#menu-button {
width: 100px;
height: 100px;
background-color: #fff;
.cerchio;
position: fixed;
left: 5px;
top: 5px;
.box-shadow;
z-index: 10;
.transistion;
}
答案 0 :(得分:2)
使用
$(window).click(function(event) {
event.preventDefault();
$('#header').animate({'top': '-100px'}, 700);
$('#menu-button').css({
left: '5px'
});
return false
});
答案 1 :(得分:1)
使用stopPropagation()
防止事件冒泡
$('#menu-button').click(function() {
$('#menu-button').css('left', '-130px');
$('#header').animate({'top': '0px'}, 700);
return false;
});
$(window).click(function(event) {
event.stopPropagation();
$('#header').animate({'top': '-100px'}, 700);
$('#menu-button').css({
left: '5px'
});
});
<强>更新强>
要防止“菜单”一词立即显示,您可以向.animate
添加一个回调函数,该函数将在标题完成动画后运行:
$('#header').animate({'top': '-100px'}, 700, function(){
$('#menu-button').css({left: '5px'});
});
更新2
为防止动画冒泡,请添加.stop()
$('#header').stop().animate({'top': '0px'}, 700);
答案 2 :(得分:1)
$('#menu-button').click(function() {
$('#menu-button').css('left', '-130px');
$('#header').animate({'top': '0px'}, 700);
return false;
});
$(window).click(function(event) {
event.stopPropagation();
$('#header').animate({'top': '-100px'}, 700);
$('#menu-button').css({
left: '5px'
});
});
&#13;
#header{
width: 100%;
height: 100px;
overflow: hidden;
position: fixed;
top: -100px;
left: 0;
background-color: green;
z-index: 10;
}
#menu-button{
background-color: #fff;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<nav id="header">
<ul>
<li><a href="page1.html" title="">1</a></li>
<li><a href="page2.html" title="">2</a></li>
<li><a href="page3.html" title="">3</a></li>
</ul>
</nav>
<!-- header ends here -->
<button id="menu-button">Menu</button>
&#13;