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

问题描述:

我想在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> 
+0

你也可以发布你的'html'吗? –

+0

@GuruprasadRao,我现在发布:) – User014019

我觉得,有一些console错误与上面的代码scrollTop,因为$(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>

+0

都将在同一页面呈现的权利? –

+1

是的,同一页。 – User014019

简单回答我是找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>