简体   繁体   English

当用户已经向下滚动页面时,如何导航到锚标记?

[英]How can I navigate to an anchor tag when user has already scrolled down page?

I've looked around, but all of the answers I've found only work when the user is at the top of the page - otherwise, it takes the user to the wrong location because it doesn't take in account how much the user has scrolled down the page. 我环顾四周,但我发现的所有答案仅在用户位于页面顶部时才有效-否则,会将用户带到错误的位置,因为它没有考虑用户的数量已向下滚动页面。 Here's what I'm trying right now ('.sidebar a' is a link to an anchor tag in the sidebar, '.site-wrap' is the scrollable div): 这是我现在正在尝试的内容(“ .sidebar a”是指向侧边栏中锚标记的链接,“。site-wrap”是可滚动的div):

$('.sidebar a').click(function() {
  var $url = $(this).attr('href');
  var $offset =  $($url).offset(); //Getting the position of the anchor
  var $currPos = $('.site-wrap').scrollTop(); //Getting the current scrolled position
  $('.site-wrap').animate({
    scrollTop: $offset.top - $currPos
  }, 1000);
  return false;
});

I can't seem to figure out why it isn't working. 我似乎无法弄清楚为什么它不起作用。 I'm a newbie, so it's probably something trivial, but I'd appreciate any pointers in the right direction. 我是一个新手,所以可能有些琐碎,但是我希望有正确方向的指导。

If I'm not mistaken, you just want to scroll the position of your element, regardless of the current scroll position. 如果我没记错的话,无论当前滚动位置如何,您都只想滚动元素的位置。

So it should be enought to take the current scroll position out of the equation and use jQuery's .position function instead of .offset : 因此,将当前滚动位置移出等式并使用jQuery的.position函数而不是.offset应该足够了:

$('.sidebar a').click(function() {
  var $url = $(this).attr('href');
  var $offset =  $($url).position(); //Getting the position of the anchor
  $('.site-wrap').animate({
    scrollTop: $offset.top
  }, 1000);
  return false;
});

This works, if the current element is a direct child of .site-wrap . 如果当前元素是.site-wrap的直接子代,则此方法有效。

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

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