简体   繁体   English

链接到同一页面上的锚点减去一些像素

[英]Link to Anchor on the same page minus some pixels

I integrated smooth scrolling to an anchor to my page. 我将平滑滚动集成到了页面的锚点中。 It works great with the code: 它非常适合以下代码:

$(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
            }, 1000);
            return false;
          }
        }
      });
    });

Now when i click a link, it scrolls to that position. 现在,当我单击链接时,它会滚动到该位置。 But since i got a fixed menubar on the top (height: 100px), it overlaps the content a bit. 但是因为我在顶部有一个固定的菜单栏(高度:100像素),所以它与内容有点重叠。 Can i fix this somehow? 我可以以某种方式解决此问题吗? like say in the code: scroll to that anchor minus 100px... i thought it might work with 就像在代码中说的那样:滚动到减去100px的锚点...我认为它可能与

scrollTop: target.offset(-100).top

is that right? 那正确吗?

jQuery's offset is a function to just give you an elements offset. jQuery的offset是只为您提供元素偏移的函数。 This is not mean to change the offset itself. 这并不意味着要更改偏移量本身。 Just substract the 100px afterwards. 之后只减去100px。

scrollTop: target.offset().top - 100

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

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