【问题标题】:How to use jQuery to scroll down the page slowly?如何使用jQuery慢慢向下滚动页面?
【发布时间】:2019-04-10 22:32:24
【问题描述】:

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

我使用 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>

【问题讨论】:

  • 因为“this.hash”未定义而出现错误,因此在“hash”变量中未定义。

标签: jquery jquery-animate


【解决方案1】:

我认为您需要更正您使用的哈希值。检查下面的链接以了解哈希在 jQuery 中是如何工作的。 How does $(this.hash) work?

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

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

【讨论】:

  • 非常感谢您的回答!了解哈希对我有什么帮助:)
【解决方案2】:

你可以使用下面的代码作为你的 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);
          }
      });
    });

【讨论】:

    猜你喜欢
    • 2015-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-03
    • 1970-01-01
    • 2012-01-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多