基于滚动位置动态更改 href

3
我正在尝试更改“下一个”按钮的href,以便单击它将继续将用户移动到博客页面上的下一个锚点。由于用户可以滚动而不使用下一个按钮,因此每当滚过一个锚点时,href都需要更改。该按钮相对于窗口定位固定,因此保持可见。
令人沮丧的是,我收到了不一致的结果-第一次向下滚动页面时,链接更新为#post-1和#post-2,但是post-2似乎没有更新href到#post-3。然后,post-3将href更新为#post-4(该位置不存在,但这暂且不提)。但是,从底部向上滚动时,post-2突然起作用,而其他位置则不起作用。以下是相关代码:
HTML:
<span id="post-0" class="anchor"></span>
  <div class="row blog-page">
    <a href="#post-1" id="blog-next">
      <i class="blog-arrow fa fa-chevron-down"></i>
    </a>
  </div>

<span id="post-1" class="anchor"></span>
  <div class="row blog-page">
    <h3>header</h3>
  </div>

<span id="post-2" class="anchor"></span>
  <div class="row blog-page">
    <h3>header</h3>
  </div>    

<span id="post-3" class="anchor"></span>
  <div class="row blog-page">
    <h3>header</h3>
  </div>

JS:

<script type="text/javascript">
   $(document).ready(function(){
      $(function () {
        var nextHash = 0;
           $(document).scroll(function () {
              $('.anchor').each(function () {
                 var top = window.scrollY;
                 var distance = top - $(this).offset().top;
                 var hash = parseInt($(this).attr('id').slice(5));

                 if (distance < 30 && distance > -30 && nextHash != hash) {
                    nextHash = hash + 1;
                    document.getElementById('blog-next').setAttribute('href', '#post-' + nextHash);
                 }
              });
           });
       });
   });
</script>

您可以在这里查看我的实时代码(它在右下角,是向下的箭头):www.zaplings.com/blog
感谢您的帮助。

在处理scroll事件时要小心。该事件会频繁触发,可能会影响页面性能。请参考http://ejohn.org/blog/learning-from-twitter/。 - Chad Killingsworth
感谢 @ChadKillingsworth,我已经取消了滚动事件。 - dannypernik
3个回答

1

使用像waypoints这样的库。

然后你就不需要担心距离、滚动等问题,只需关注回调函数即可。


万岁!谢谢你把这个传递下去。 - dannypernik

0
这是我使用 Waypoints 的解决方案,以防其他人遇到同样的问题。
        $(document).ready(function(){

            $('.anchor').each(function () {
                new Waypoint({
                    element: this,
                    handler: function(direction) {

                        var previousWaypoint = this.previous();
                        var nextWaypoint = this.next();

                        if (this != this.group.last()){
                            document.getElementById('blog-next').setAttribute('href','#' + nextWaypoint.element.id)
                            $('#blog-next').show();
                        } else {
                            $('#blog-next').hide();
                        };
                    }
                })
            })
         });

0

我认为当你滚动页面时,你的距离变量可能会超出 -30 < x < 30 的范围,因此你会错过触发点。

看一下这个链接:检查滚动后元素是否可见

你可以使用“isScrolledIntoView”函数,然后使用jquery选择当前滚动到视图元素的下一个兄弟元素。然后,将你的锚点更改为链接到它。


谢谢您的回复,看起来使用航点是避免性能问题的好方法。 - dannypernik

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接