简体   繁体   English

如何设置平滑滚动的偏移量

[英]How to Set Offsett for Smooth Scroll

I have implemented the CSS Tricks Smooth Page Scroll on my site and it's working pretty nicely.我已经在我的网站上实现了CSS Tricks Smooth Page Scroll ,它运行得非常好。 However, because I have a fixed nav at the top of the page, when the page scrolls to the appropriate anchor div, the top of the div disappears behind the nav.但是,因为我在页面顶部有一个固定的导航,所以当页面滚动到相应的锚点 div 时,该 div 的顶部消失在导航后面。 How can I offset the scroll (about 70px) so that the whole div is shown?如何偏移滚动(大约 70px)以便显示整个 div? I tried doing this:我尝试这样做:

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

But that doesn't quite work.但这并不完全有效。 The page scrolls to the appropriate spot but then it immediately jumps back up so that the top of the div is hidden.页面滚动到适当的位置,但随后立即跳回以隐藏 div 的顶部。 What am I missing?我错过了什么? Here's the code in full:这是完整的代码:

$(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 [];
    }

});

Thanks in advance for your help.在此先感谢您的帮助。

This always happens. 这总是发生。 I search and search for an answer, get frustrated, post a question asking for help, and then immediately find an answer to my problem. 我搜索并搜索答案,感到沮丧,发布问题寻求帮助,然后立即找到问题的答案。 Silly. 愚蠢。 Anyway, here's the solution for anyone who might be having the same problem. 无论如何,对于可能遇到同样问题的人来说,这是解决方案。

If you want to change the offset by 70px, for example, change the code to this: 例如,如果要将偏移量更改为70px,请将代码更改为:

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

However, unless you remove this line from the code... 但是,除非您从代码中删除此行...

location.hash = target;

... the page will scroll to the right spot and then immediately jump back up so that the top of the div is hidden behind the header. ...页面将滚动到正确的位置,然后立即向上跳回,以便div的顶部隐藏在标题后面。 You can remove the above line from the code and everything will work great, except for the fact that the URL will no longer change to reflect the user's position on the page. 您可以从代码中删除上述行,除了URL不再更改以反映用户在页面上的位置这一事实外,一切都会很好用。

If you want the URL to change (and I think this is a good idea for usability purposes), then all you have to do is change the CSS for the anchor divs. 如果您希望更改URL(我认为这对于可用性目的而言是个好主意),那么您所要做的就是更改锚点div的CSS。 Add a positive value for padding-top and a negative value for margin-top. 为padding-top添加正值,为margin-top添加负值。 For example: 例如:

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

I only have 3 divs, so I just plugged in that CSS to each of them and voila, everything worked. 我只有3个div,所以我只是为每个人插入了CSS,瞧,一切正常。 However, if you have a lot of anchor divs, you might consider creating a class of .anchor, putting the CSS there, and applying the class to all the appropriate divs. 但是,如果你有很多锚div,你可以考虑创建一个.anchor类,将CSS放在那里,并将类应用于所有适当的div。

I hope this helps! 我希望这有帮助!

I have fixed such a kind of issue with below code: 我用下面的代码解决了这样一个问题:

Working demo HERE . 这里工作演示。 You can play with " Post Topics " section in the sidebar and content in the main-content area. 您可以使用侧栏中的“ 帖子主题 ”部分和主要内容区域中的内容。

Code

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;
      }
    }
  });
});

Refer to https://codepen.io/pikeshmn/pen/mMxEdZ 请参阅https://codepen.io/pikeshmn/pen/mMxEdZ

Approach: We get the height of fixed nav using document.getElementById('header').offsetHeight And offset the scroll to this value. 方法:我们使用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;
  });

Actually there's a CSS rule for that : scroll-padding-top :) Combined with a regular padding-top for the top-most element of course.实际上有一个 CSS 规则: scroll-padding-top :) 当然,与常规的padding-top用于最顶部的元素。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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