简体   繁体   中英

How do I prevent the browser window from jumping back to the top of the page when when I open and close my panel?

I've been working on a website that has a persistent header, with a navigation panel that slides out of the top of the screen. It currently works by wrapping the header and navigation panel in a fixed div, and giving that div a negative top margin equal to the height of the navigation.

The HTML

<div class="sticky">
  <div class="above-header">
    This is the navigation panel.
  </div>

  <div class="header">
    This is a logo
    <a href="#" class="toggle">Toggle</a>
  </div>
</div>

The CSS

.sticky {
  height:300px;
  margin:-250px 0 0;
  position:fixed;
  z-index:1000;
}

.above-header {
  height:250px;
}

.header {
  height:50px;
}

.open {
  margin:0
}

Then I use a tiny js/jquery script to change that margin to 0, making the navigation visible.

$('a.toggle').click(function() {
    if ($('.sticky').hasClass('open')){  
        $('.sticky').removeClass('open');
      }
      else{
        $('.sticky').addClass('open');
      }
});

I've got it working fine except for one problem: if I open or close the panel, the view jumps up to the top of the page, regardless of where I've scrolled to.

I've recreated a simplified version of the problem on Codepen to demonstrate what I'm talking about.

I cannot imagine why it is doing this, and my Google Fu hasn't turned up any answers. Any idea what I can do to fix this problem? Or perhaps there's a better technique for this that I'm not aware of?

Instead of

<a href="#">

Use

<a href="javascript:void(0);">

Just prevent the default action (nl navigating to your url + #)

$('a.toggle').click(function(e) {
    e.preventDefault();
    $('.sticky').toggleClass('open');
});

and with the toggleClass option, you can simplify your call :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM