使用if else点击停止页面跳转到顶部

时间:2014-10-17 18:23:47

标签: jquery

我有一个切换菜单的按钮(#menu-toggle)。当用户单击按钮时,页面跳转到顶部。我怎么能阻止这种情况发生?

试过这个,但它不起作用:

$('#menu-toggle').click(function(event){
$('.wrap, nav > ul, .wrap > .container:first-child').toggleClass('push');
    event.preventDefault();
if ($('.wrap').hasClass('push')){
    $('.wrap').css('position', 'fixed');
    $('.wrap > .container:first-child > div:first-child').slideUp(500);
} else {
    $('.wrap').css('position', 'relative');
}
});

这是我的HTML:

<button id="menu-toggle">
  <div id="nav-toggle"><span></span></div>
</button>
<button id="search-toggle"></button>

任何帮助都将不胜感激。

由于

1 个答案:

答案 0 :(得分:0)

解决方案可能就是解决问题 完成 else block 返回fals e或 event.preventDefault()不在if语句之前 >,你可以使用这样的东西:

$('#menu-toggle').click(function(event){
$('.wrap, nav > ul, .wrap > .container:first-child').toggleClass('push');

if ($('.wrap').hasClass('push')){
    $('.wrap').css('position', 'fixed');
    $('.wrap > .container:first-child > div:first-child').slideUp(500);
} else {
    $('.wrap').css('position', 'relative');
}
event.preventDefault(); //equivalent to return false;
});