【问题标题】:scrollTop equal to 0 even though the div is further down the page即使 div 位于页面下方,scrollTop 也等于 0
【发布时间】:2017-06-09 18:16:54
【问题描述】:

我有 2 个 div。一个包含页面上部的部分。另一个在顶部 div 的正下方。第二个 div 大约是页面下方的 1.5 个视口。但是当我尝试在按下导航按钮时让页面滚动到第二个 div 时。它把我带到了页面的顶部。即使它引用了第二个 div 的 scrollTop 属性。

【问题讨论】:

标签: javascript jquery html css scrolltop


【解决方案1】:

scrollTop 将始终等于位置 0。如果要滚动到不同的 div,则需要使用偏移量并滚动到哈希位置。如果您使用的是 Bootstrap,则可以为此使用 ScrollSpy。如果没有,那么您可以使用此代码来处理平滑滚动到哈希位置。

在您的情况下,哈希应该是 div 的 ID - 您将通过在按钮/链接上设置 a href 以匹配您希望按钮/链接滚动到的 div 的 ID 来定位它。

因此,您的链接可能如下所示:

 <a href="#somediv">Some Link</a>

您的 div 可能如下所示:

 <div class="someclass" id="somediv"></div>

这个 JS 会处理滚动到正确的位置:

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top -80
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

【讨论】:

  • 你在使用 jQuery 吗?抱歉 - 忘了提到该解决方案需要 jQuery。
  • gyazo.com/929adadba37e90537668b013e4ecab2d 我需要添加什么才能让它做我想做的事情? 3
  • #hobbitsandinterests 是按钮的 ID
猜你喜欢
  • 1970-01-01
  • 2022-11-21
  • 2013-12-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多