滚动到带有偏移量的 div ID [英] Scroll to div ID with offset

查看:40
本文介绍了滚动到带有偏移量的 div ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在 Wordpress 上运行一个测试站点.我的页面有几个带有 ID 的 div,顶部有一个菜单,带有指向这些 ID 的锚点.我的标题是粘性的,所以当我单击一个锚点时,它会导航到 div ID,但 div 的开头隐藏在标题下方.我希望这样,当我单击一个锚点时,它会导航到 div,但它上方的像素很少.我设法做到了,尽管有点问题.

I am currently runnning a test site on Wordpress. I have my page with several divs which have IDs and a menu on top with anchors which lead to those IDs. 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. I would like it so that when I click an anchor, it navigates to the div, but few pixels above it. 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);

会发生什么:

  1. 我点击带有 href="#someid" 的锚点
  2. 我的浏览器导航到偏移量为 - 90px 的 #someid(到目前为止效果很好)
  3. 然后我的浏览器向下滚动 90px,到 div #someid 在视口开头(和粘性标题后面)开始的位置.
  4. 最后我的 URL 更改为 http://example.com/#someid

我只想删除第 3 步.非常感谢任何帮助.

I just want to delete step 3. Any help is much appreciated.

更新:我刚刚发现我的主题安装了 jQueryOne-page-nav"插件并且它正在干扰.仍在尝试了解它是如何工作的,以及我是否可以修改它以具有偏移量

Update: I just found out my theme has jQuery "One-page-nav" plugin installed and it is interfering. Still trying to understand how it works and if I can modify it to have offsets

推荐答案

我遇到了同样的问题,就我而言,我通过添加 padding-top 和相同值的负边距顶部解决了这个问题:

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:

.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.

我希望我能以一种可以理解的方式解释这一点......这在我的脑海中肯定是有道理的:D

I hope I'm explaining this in a way that's understandable... It sure makes sense in my head :D

这篇关于滚动到带有偏移量的 div ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆