【问题标题】:How to smooth scroll using location.hash?如何使用 location.hash 平滑滚动?
【发布时间】:2016-12-02 07:06:32
【问题描述】:

我正在尝试在 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>

【问题讨论】:

  • 你也可以发布你的html吗?
  • @GuruprasadRao,我现在发布了 :)

标签: javascript jquery scroll smooth-scrolling


【解决方案1】:

我觉得,您的上述代码对scrollTop 有一些console 错误,因为$(test_function).target. 将未定义。您需要定位正确的element 才能顺利导航到它。以下是您可以使用的示例 sn-p。

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>

【讨论】:

  • 它不工作。 &lt;a href&gt; 放在另一个页面中,而 div 也放在另一个页面中
  • 现在好了。 :)
  • 酷..快乐编码..:)
【解决方案2】:

简单的答案我找到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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 2018-04-03
    • 2011-02-12
    • 2021-06-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多