2016-05-10 79 views
0

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

以下是我的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> 

任何帮助将不胜感激。

+0

尝试将您的选择器从$('a [href * =#]:not([href =#])'')更改为$('a')并进行测试。有时只是选择器有一个你无法接受的错误。 – Brett

+0

你需要引用属性选择器的值$('a [href^=“#”]:not([href =“#”]') – Steffen

回答

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工作。让我知道什么是给你的问题。

+0

它仍然不起作用。在Chrome中,它阻止它,它不会跳到没有滚动的锚点,它只是不动。 – brodym46

+0

我更新了。看看codepen,如果仍然无法使用,请告诉我看看发生了什么 –

+0

它仍然没有工作,甚至不是代码不工作,它只是跳转到锚点,页面不移动,当我拿出代码时,它跳转正确的位置 – brodym46