2

我正在制作一个在中心顶部带有粘性导航的单页网站,宽度约为 1000 像素,高度约为 20-25 像素,现在我还包括平滑滚动功能,但我的问题是每当页面滚动到它的活动页面时,标题隐藏在粘性导航下,我如何获得粘性导航底部的偏移量?谢谢。

这是js代码顺便说一句:

$('a').click(function(e) {
        var target = $(this).attr('href');
        e.preventDefault();

        $('html,body').animate({
            scrollTop: $(target).offset().top
        }, 800, 'easeInOutCirc');
    });
4

3 回答 3

5

保持当前代码不变并将该偏移量添加到网站顶部的最简单方法是在 .top 之后添加所需的偏移量值,如下所示:

$('a').click(function(e) {
    var target = $(this).attr('href');
    e.preventDefault();

    $('html,body').animate({
        scrollTop: $(target).offset().top - 20
    }, 800, 'easeInOutCirc');
});

希望这个答案没有最后一个那么复杂。:)

于 2012-08-17T15:20:42.713 回答
2

jQuery 的.position()方法将为您提供元素相对于页面的顶部和左侧偏移量。因此,您只需要将.outerHeight()粘性导航添加到它的.position().top值。

这是一个例子:http: //jsfiddle.net/NUfaZ/1/

当您在页面中向下滚动时,您会看到它的位置得到更新。

于 2011-10-08T12:54:47.120 回答
0

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

PS:

  • 它包括标题和目标之间的 5 像素差异
  • 滚动效果不硬,比较流畅;平滑滚动
于 2017-08-20T09:38:01.323 回答