如何使用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>

我在这里找到的简单答案,您也可以使用多个锚标记和不同的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>

最新更新