简体   繁体   中英

Smooth scrolling workaround

I'm working with nav bar that becomes fixed at max-width 1000px. The height is 60px.

My problem is page jump will not reach the place it should.

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        if (target.length <= 1000) {
          $('html,body').animate({
            scrollTop: target.offset().top - 60
          }, 1000);
        };
        return false;
      }
    }
  });
});

Did it! this will go backwards 60px with a max-width screen of 1000px

$(function() {
  $('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        $('html,body').animate({
          scrollTop: target.offset().top
        }, 1000);
        if (matchMedia('only screen and (max-width: 1000px)').matches) {
        $('html,body').animate({
          scrollTop: target.offset().top -60
        }, 1000);

        return false;
      }
    }}
  });
});

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