如何使用jQuery慢慢向下滚动页面?

问题描述 投票:1回答:2

我试图在单击按钮时获得慢滚动效果。现在我找到了一个函数,当单击一个元素时跳转到页面的哈希。

我使用scrolltop方法跳下我的页面。我走了-220页面。

浏览器中的错误消息:

Uncaught TypeError: Cannot read property 'top' of undefined
at HTMLDivElement.<anonymous> (script.js:35)
at HTMLDivElement.dispatch (jquery.min.js:2)
at HTMLDivElement.y.handle (jquery.min.js:2)

欢迎任何帮助。如果您有疑问,请询问。

码:

$(document).ready(function() {
  $("#choose-time div").on('click', function(event) {
    $(this).toggleClass("selectedBox");

    if (this.hash !== '') {
      event.preventDefault();
      var hash = this.hash;

      $("html, body").animate({
        scrollTop: $(hash).offset().top - 220
      }, 900);
    }
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section id="choose-time">
  <h2>Kies een Datum</h2>
  <div>
    <p>Donderdag</p>
    <p>28/04/2019</p>
  </div>
  <p><strong>Click</strong> de gewenste datum aan a.u.b</p>
</section>
jquery jquery-animate
2个回答
0
投票

我认为你需要纠正你使用过的哈希值。查看下面的链接,了解哈希在jQuery中的工作原理。 How does $(this.hash) work?

第二个选项,您可以使用特定的ID或类并增加时间

    $("html, body").animate({
      scrollTop: $("#elementId").offset().top - 220
    }, 4000);

0
投票

您可以使用下面的代码作为您的jQuery

$(document).ready(function(){
      $("#choose-time div").on('click', function(event){
        $(this).toggleClass("selectedBox");
          var hash = $(this).offset().top - 220;
          if(hash !== ''){
            event.preventDefault();

            $("html, body").animate({
              scrollTop: hash
            }, 900);
          }
      });
    });
© www.soinside.com 2019 - 2024. All rights reserved.