如果我使用 JQuery $(window).click(function() 关闭菜单,菜单的墨水不起作用

Menu's inks doesn't work if i use JQuery $(window).click(function() to close the menu

本文关键字:菜单 不起作用 墨水 function JQuery window click 如果      更新时间:2023-09-26

大家晚上好,我正在使用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;
}

使用

$(window).click(function(event) {
        event.preventDefault();
        $('#header').animate({'top': '-100px'}, 700);

        $('#menu-button').css({
            left: '5px'
        });
    return false
});

使用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'
    });
});

小提琴

更新

为了防止单词"menu"立即出现,您可以在.animate中添加一个回调函数,该函数将在标头完成其动画后运行:

$('#header').animate({'top': '-100px'}, 700, function(){
    $('#menu-button').css({left: '5px'});
});

小提琴 2

更新 2

要防止动画冒泡,请添加.stop()

$('#header').stop().animate({'top': '0px'}, 700);

小提琴 3

$('#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'
    });
});
#header{
width: 100%;
height: 100px;
overflow: hidden;
position: fixed;
top: -100px;
left: 0;
background-color: green;
z-index: 10;
}
#menu-button{
background-color: #fff;
}
<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>