【问题标题】:Page jumps up instead of scrolling up页面向上跳而不是向上滚动
【发布时间】:2016-03-03 14:40:24
【问题描述】:

我从另一个 Stack Overflow 问题中得到了这个代码位,但似乎有一个小问题。当我从一个部分移动到另一个部分时,哈希会正确更改,但是当我尝试向上滚动时,它会跳到最顶部,而不是平滑的手动滚动。任何帮助将不胜感激:)

HTML

<!doctype html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="style.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
    <script src="script.js"></script>
</head>
<header>
</header>
<body>
    <div class="main">
        <section id="one" class="section"></section>
        <section id="two" class="section"></section>
        <section id="three" class="section"></section>
        <section id="four" class="section"></section>
        <section id="five" class="section"></section>
        <section id="six" class="section"></section>
    </div>
</body>
</html>

这里是 JS:

$(document).scroll(function(){
    $('section').each(function(){
        if (
           $(this).offset().top < window.pageYOffset
    //begins before top
        && $(this).offset().top + $(this).height() > window.pageYOffset
    //but ends in visible area
    //+ 10 allows you to change hash before it hits the top border
        ) {
            window.location.hash = $(this).attr('id');
        }
    });
});

【问题讨论】:

  • 所以与其跳起来,不如让它像使用滚动条一样滚动?
  • jQuery scroll to element的可能重复
  • 是的,它奇怪地跳了起来,除非我再次向下滚动,否则我无法回到上一节

标签: javascript jquery html hash


【解决方案1】:

您可以使用$(window).scrollTop() 而不是pageYOffset,这将返回页面顶部与窗口中文档顶部的偏移距离。如果您希望对属性的滚动进行动画处理,您将希望滚动到具有 id 的元素的位置。如果您希望动画滚动到页面顶部,您可以这样做

$(window).animate({
  top: 0
}, 1000);

【讨论】:

    【解决方案2】:

    您可以通过在javascript中添加向上滚动动画来解决这个问题,这样我们就可以在滚动中添加延迟,从而提供完美的滚动到顶部的效果。

    Javascript

    window.onload = function() {
    // short timeout
    setTimeout(function() {
        $(document.body).scrollTop(0);
        }, 15);
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-15
      • 1970-01-01
      • 1970-01-01
      • 2014-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多