如何使用 location.hash 平滑滚动?

How to smooth scroll using location.hash?

我正在尝试在 location.hash 中添加一个平滑的滚动条,但它似乎不起作用。

如何解决这个问题?

JS

function test_function(){
    window.location.hash = '#divid';
    jQuery(document).ready(function($){
        $('html, body').animate({ scrollTop: $(test_function).target.offset().top }, 1000);
    });
}

HTML

<div>
<a href="<?php echo $_POST['referrer'] ?>#divid">Find a store</a>
</div>

我觉得,上面 scrollTop 的代码有一些 console 错误,因为 $(test_function).target. 会未定义。您需要定位正确的 element 才能顺利导航到它。以下是您可以处理的示例片段。

function test_function() {
  $('html, body').animate({
    scrollTop: $("#divid").offset().top
  }, 2000);
}
#divid {
  position: absolute;
  top: 800px;
  width: 200px;
  height: 200px;
  background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a onclick="test_function(this)" href="#">Find a store</a>
<div id="divid"></div>

我找到了简单的答案 here ,在这里你也可以使用多个锚标签和不同的 div id。

<a href="<?php echo $_POST['referrer'] ?>#divid">Find a store</a>

<script type="text/javascript">
    $(function() {
      $("a[href*='#']:not([href='#'])").click(function() {
        if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
        if (target.length) {
          $('html,body').animate({
            scrollTop: target.offset().top
          }, 2000);
          return false;
        }
      }
     });
    });
</script>

<div id="divid">Scroll Section</div>