jQuery Smooth Scroll不滚动

时间:2016-05-10 00:22:08

标签: javascript jquery html

我试图在我的网站中添加平滑滚动到命名锚点。我有一个jQuery插件,只需调用内部命名锚点并动画html和body。我以前在其他网站上使用它并且工作正常,但我无法弄清楚它为什么不在这里工作。奇怪的是,相同的代码在Apple Safari中运行良好,但在Google Chrome中运行不正常。我使用过的所有其他网站在Chrome上运行良好。我无法弄明白这一点。

以下是我的HTML。它只是一个带有标签的div和下面div中的匹配锚点。

<div id="slide1" class="slide">
<a href="#section">
<div id="scrollbtn">
<img src="images/downarrow.png" alt="Down Arrow">
</div>
</a>
</div>


<div id="main">
<a id="section" class="link"></a>
<p>Test</p>
</div>

下面是jQuery插件。它在我使用的其他网站上运行良好,我不知道它为什么不在这里工作。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(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
        }, 500);
        return false;
      }
    }
  });
});
</script>

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

    $(function() {
    $('a').bind('click',function(event){
        var $anchor = $(this);

        $('html, body').stop().animate({
            scrollTop: $($anchor.attr('href')).offset().top
        }, 800);
        event.preventDefault();
    });
});

是另一种方法。

Codepen

让Codepen工作。让我知道是什么给你带来了问题。

相关问题