jQuery滚动到锚点(减去设定的像素数量)

Joh*_*ohn 33 anchor jquery scroll

我使用以下代码使用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 [];
  }

});
Run Code Online (Sandbox Code Playgroud)

反正有没有让它滚动到那个锚点但减去一定数量的像素?(在我的情况下,我希望它去-92px)

谢谢你的帮助.

Jon*_*age 31

我必须自己解决这个问题.您需要根据要滚动的像素数量来调整偏移量.就我而言,我需要它在页面上高出50个像素.所以,我从targetOffset中减去了50.

现在,为你摇摆不定的代码部分是location.hash - 这告诉浏览器将其位置设置为特定点.在所有情况下,这是一个包含您刚刚滚动到的ID的字符串.所以,它就像'#foo'.你需要保持这个,所以我们会留下它.

但是,为了防止浏览器在设置location.hash(默认浏览器操作)时"跳转",您只需要阻止默认操作.因此,通过animate函数中的完成函数传递事件'e'.然后只需调用e.preventDefault().您必须确保浏览器实际上正在调用一个事件,否则它将会出错.因此,if-test修复了这个问题.

完成.这是修改后的代码块:

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;
      });
    });
  }
Run Code Online (Sandbox Code Playgroud)


kal*_*azy 18

这是我使用的:

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

... 50添加/减去的像素数在哪里.


Max*_*Max 14

此代码适用于我在我的网站中的任何链接锚点尊重"150px"高度修复菜单在顶部.

<!-- 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 -->
Run Code Online (Sandbox Code Playgroud)


小智 5

大声笑)

<span class="anchor" id="section1"></span>
<div class="section"></div>

<span class="anchor" id="section2"></span>
<div class="section"></div>

<span class="anchor" id="section3"></span>
<div class="section"></div>

<style>
.anchor{
  display: block;
  height: 115px; /*same height as header*/
  margin-top: -115px; /*same height as header*/
  visibility: hidden;
}
</style>
Run Code Online (Sandbox Code Playgroud)