【问题标题】:How to Set Offsett for Smooth Scroll如何设置平滑滚动的偏移量
【发布时间】:2012-10-28 22:35:26
【问题描述】:

我已经在my site 上实现了CSS Tricks Smooth Page Scroll,它工作得很好。但是,因为我在页面顶部有一个固定的 nav,所以当页面滚动到适当的锚 div 时,div 的顶部会消失在 nav 后面。如何偏移滚动(大约 70 像素)以便显示整个 div?我试过这样做:

var targetOffset = $target.offset().top - 70;

但这并不完全奏效。页面滚动到适当的位置,但随后它立即跳回以隐藏 div 的顶部。我错过了什么?这是完整的代码:

$(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');

    // Any links with hash tags in them (can't do ^= because of fully qualified URL potential)
    $('a[href*=#]').each(function() {

        // Ensure it's a same-page link
        var thisPath = filterPath(this.pathname) || locationPath;
        if (  locationPath == thisPath
            && (location.hostname == this.hostname || !this.hostname)
            && this.hash.replace(/#/,'') ) {

                // Ensure target exists
                var $target = $(this.hash), target = this.hash;
                if (target) {

                    // Find location of target
                    var targetOffset = $target.offset().top - 70;
                    $(this).click(function(event) {

                        // Prevent jump-down
                        event.preventDefault();

                        // Animate to target
                        $(scrollElem).animate({scrollTop: targetOffset}, 400, function() {

                            // Set hash in URL after animation successful
                            location.hash = target;

                        });
                    });
                }
        }

    });


    // Use the first element that is "scrollable"  (cross-browser fix?)
    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 [];
    }

});

提前感谢您的帮助。

【问题讨论】:

  • 我发现了这个link,它帮助我理解了它跳跃的原因是因为它在动画之后重置了 URL。所以现在我有一个新问题,有什么办法可以重置 URL 并摆脱跳跃?我希望 URL 能反映用户在页面上的位置。

标签: javascript jquery scroll offset smooth-scrolling


【解决方案1】:

这总是发生。我搜索并寻找答案,感到沮丧,发布问题寻求帮助,然后立即找到我的问题的答案。愚蠢的。无论如何,这里是为可能遇到相同问题的任何人提供的解决方案。

如果你想改变70px的偏移量,例如,把代码改成这样:

var targetOffset = $target.offset().top - 70;

但是,除非您从代码中删除此行...

location.hash = target;

...页面将滚动到正确的位置,然后立即跳回,这样 div 的顶部就隐藏在标题后面。您可以从代码中删除上面的行,一切都会很好,除了 URL 将不再更改以反映用户在页面上的位置。

如果您希望更改 URL(我认为这对于可用性而言是一个好主意),那么您所要做的就是更改锚 div 的 CSS。为 padding-top 添加一个正值,为 margin-top 添加一个负值。例如:

#anchor-name {
padding-top: 70px;
margin-top: -70px;
}

我只有 3 个 div,所以我只是将 CSS 插入到每个 div 中,瞧,一切正常。但是,如果您有很多锚 div,您可能会考虑创建一个 .anchor 类,将 CSS 放在那里,并将该类应用于所有适当的 div。

我希望这会有所帮助!

【讨论】:

  • 哦,如果你正在使用 Twitter Bootstrap 的 scrollspy,别忘了在代码中调用 scrollspy 功能的地方添加 data-offset="70"。它应该看起来像这样:&lt;body data-spy="scroll" data-offset="70" &lt;?php body_class(); ?&gt; &gt;.
【解决方案2】:

我已经用下面的代码解决了这样的问题:

工作演示HERE。您可以使用侧边栏中的“发布主题”部分和主要内容区域中的内容。

代码

jQuery(function() {
  jQuery('a[href*=#]:not([href=#])').click(function() {
    if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {

      var target = jQuery(this.hash);
      target = target.length ? target : jQuery('[name=' + this.hash.slice(1) +']');
      if (target.length) {
        jQuery('html,body').animate({
          scrollTop: target.offset().top -100
        }, 1000);
        return false;
      }
    }
  });
});

【讨论】:

  • 在您遇到错误Uncaught Error: Syntax error, unrecognized expression: a[href*=#]:not([href=#]) 的情况下。就像这样 a[href*=\\#]:not([href=\\#])' 逃避#
【解决方案3】:

参考https://codepen.io/pikeshmn/pen/mMxEdZ

方法:我们使用 document.getElementById('header').offsetHeight 得到固定导航的高度 并将滚动偏移到这个值。

var jump=function(e){  

e.preventDefault();                        //prevent "hard" jump
  var target = $(this).attr("href");       //get the target

      //perform animated scrolling
      $('html,body').animate(
        {
          scrollTop: $(target).offset().top - document.getElementById('header').offsetHeight - 5  //get top-position of target-element and set it as scroll target
        },1000,function()                  //scrolldelay: 1 seconds
        {
          location.hash = target;          //attach the hash (#jumptarget) to the pageurl
        });
      }

  $(document).ready(function()
  {
    $('a[href*="#"]').bind("click", jump); //get all hrefs
    return false;
  });

【讨论】:

    【解决方案4】:

    实际上有一个 CSS 规则:scroll-padding-top :) 结合常规的padding-top 当然是最顶层的元素。

    参见。 https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-padding-top

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多