简体   繁体   English

滚动到带有偏移量的div ID

[英]Scroll to div ID with offset

I am currently runnning a test site on Wordpress. 我目前正在Wordpress上运行一个测试站点。 I have my page with several divs which have IDs and a menu on top with anchors which lead to those IDs. 我的页面上有多个div,这些div具有ID,并且菜单顶部带有指向这些ID的锚点。 My header is sticky, so when I click an anchor, it navigates to the div ID, but the beginning of the div stays hidden below the header. 我的标题是粘性的,因此当我单击锚点时,它会导航到div ID,但div的开头仍隐藏在标题下方。 I would like it so that when I click an anchor, it navigates to the div, but few pixels above it. 我想要这样,以便当我单击锚点时,它可以导航到div,但其上方只有几个像素。 I managed to do that, though with a little problem. 我设法做到了,尽管有一点问题。

(function($,document){
  $("a[href^='#']").click(function(){
    var url = $(this).attr('href');
    $('html,body').animate({scrollTop: $(url).offset().top - 90}, 2000);
  });
})(jQuery);

What happens is: 发生的是:

  1. I click an anchor with a href="#someid" 我单击带有href =“#someid”的锚点
  2. My browser navigates to the #someid with offset of - 90px (It works perfectly so far) 我的浏览器导航到#someid,偏移量为-90px(到目前为止,它可以正常运行)
  3. Then my browser scrolls 90px down, to the position where the div #someid starts at the beginning of the viewport (and behind the sticky header). 然后,我的浏览器向下滚动90px,直到div #someid在视口的开始处(在粘性标头之后)开始的位置。
  4. Finally my URL changes to http://example.com/#someid 最后,我的网址更改为http://example.com/#someid

I just want to delete step 3. Any help is much appreciated. 我只想删除步骤3。非常感谢您的帮助。

Update: I just found out my theme has jQuery "One-page-nav" plugin installed and it is interfering. 更新:我刚刚发现我的主题安装了jQuery“ One-page-nav”插件,并且该插件存在干扰。 Still trying to understand how it works and if I can modify it to have offsets 仍在尝试了解其工作原理以及是否可以对其进行修改以具有偏移量

I was having the same issue and in my case I solved it by adding padding-top and a negative margin-top of the same value: 我遇到了同样的问题,在我的情况下,我通过添加相同值的padding-top和负margin-top解决了此问题:

.some-class {
  padding-top: 4em;
  margin-top: -4em;
}

By doing this my element looks like it's on the exact same location but the browser finds it sooner while scrolling. 这样,我的元素看起来就在完全相同的位置,但是浏览器在滚动时会更快地找到它。 You can set these values to the height of your sticky header or play around to make sure the heading is exactly where you want it to be. 您可以将这些值设置为粘性页眉的高度,或四处游动以确保标题正好位于您想要的位置。

I hope I'm explaining this in a way that's understandable... It sure makes sense in my head :D 我希望我以一种可以理解的方式来解释这一点...在我脑海中这确实是有道理的:D

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

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