2016-12-02 113 views
0

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

回答

1

我覺得,有一些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

0

簡單回答我是找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>