jQuery scroll to anchor (minus set amount of pixel

2020-02-17 06:18发布

I am using the following code to scroll to anchor points with jQuery:

$(document).ready(function() {
  function filterPath(string) {
  return string
    .replace(/^\//,'')
    .replace(/(index|default).[a-zA-Z]{3,4}$/,'')
    .replace(/\/$/,'');
  }
  var locationPath = filterPath(location.pathname);
  var scrollElem = scrollableElement('html', 'body');

  $('a[href*=#]').each(function() {
    var thisPath = filterPath(this.pathname) || locationPath;
    if (  locationPath == thisPath
    && (location.hostname == this.hostname || !this.hostname)
    && this.hash.replace(/#/,'') ) {
      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = target;
          });
        });
      }
    }
  });

  // use the first element that is "scrollable"
  function scrollableElement(els) {
    for (var i = 0, argLength = arguments.length; i <argLength; i++) {
      var el = arguments[i],
          $scrollElement = $(el);
      if ($scrollElement.scrollTop()> 0) {
        return el;
      } else {
        $scrollElement.scrollTop(1);
        var isScrollable = $scrollElement.scrollTop()> 0;
        $scrollElement.scrollTop(0);
        if (isScrollable) {
          return el;
        }
      }
    }
    return [];
  }

});

Is there anyway to make it scroll to that anchor but minus a set amount of pixels? (in my case i want it to go -92px)

Thanks for any help.

9条回答
小情绪 Triste *
2楼-- · 2020-02-17 06:54

Not wanting to learn Javascript and always looking for the easiest option, just create an empty DIV above the anchor point you want to land at then in CSS make the div

anchorpointl{margin-top: -115px;}

or however far above or below you want to go and the jobs done

查看更多
祖国的老花朵
3楼-- · 2020-02-17 06:57

I just had to solve this problem myself. You need to adjust your offset by the amount of pixels you want to scrollTo. In my case, I needed it to be 50 pixels higher on the page. So, I subtracted 50 from targetOffset.

Now, the part of the code that's throwing a wobbly for you is location.hash - this is telling the browser to set its location to a specific point. In all cases, this is a string containing the ID you just scrolled to. So, it'd be something like '#foo'. You need to maintain this, so we'll leave it.

However, to prevent the browser from 'jumping' when location.hash is set (a default browser action), you simply need to prevent the default action. So, pass your event 'e' through the completion function in the animate function. Then simply call e.preventDefault(). You'll have to make sure that the browser is actually calling an event, otherwise it will error out. So, an if-test fixes that.

Done. Here's the revised code chunk:

if (target) {
    var targetOffset = $target.offset().top - 50;
    $(this).click(function(event) {
      if(event != 'undefined') {
          event.preventDefault();}
      $(scrollElem).animate({scrollTop: targetOffset}, 400, function(e) {
          e.preventDefault();
          location.hash = target;
      });
    });
  }
查看更多
做自己的国王
4楼-- · 2020-02-17 06:57

I was unable to use Jonathan Savage's solution as I couldn't pass an event callback into animate() without error. I had this issue today and found a simple solution:

      var $target = $(this.hash), target = this.hash;
      if (target) {
        var targetOffset = $target.offset().top - 92;
        $(this).click(function(event) {
          event.preventDefault();
          $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {
            location.hash = targetOffset;
          });
        });

Subtract your pixel offset from the targetOffset variable, then assign location.hash to that variable. Stops the page jumping when scrolling to the target hash.

查看更多
不美不萌又怎样
5楼-- · 2020-02-17 07:02

Here is what i use. Set the offset to what you need.

$('a[href^="#"]').click(function(e) {
  e.preventDefault();
  $(window).stop(true).scrollTo(this.hash {duration:1000,interrupt:true,offset: -50});
});
查看更多
相关推荐>>
6楼-- · 2020-02-17 07:03

This code work for me in any link anchor in my site respect "150px" height for fix menu on top.

<!-- SMOOTH SCROLL -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(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-150
        }, 1000);
        return false;
      }
    }
  });
});
</script>
<!-- End of SMOOTH SCROLL -->
查看更多
Viruses.
7楼-- · 2020-02-17 07:05

This is what I use:

function scrollToDiv(element){
    element = element.replace("link", "");
    $('html,body').unbind().animate({scrollTop: $(element).offset().top-50},'slow');
};

...where 50 is the number of pixels to add/subtract.

查看更多
登录 后发表回答