jQuery Smooth Scrolling

bnt*_*rns 7 html jquery smooth-scrolling jquery-animate

我试图实现平滑滚动到信息索引.我看过这个jsFiddle http://jsfiddle.net/9SDLw/,我无法让它工作.将代码插入HTML文档或其他什么地方是否重要?

这是我的代码:

JS(文件负责人):

<script type="text/javascript">
$('a').click(function(){
    $('html, body').animate({
        scrollTop: $( $(this).attr('href') ).offset().top
    }, 500);
    return false;
});?
</script>
Run Code Online (Sandbox Code Playgroud)

标记:

链接

<a href = "#G" rel = "" id="G" class="anchorLink">G</a><br />
Run Code Online (Sandbox Code Playgroud)

<a name = "G" id="G"><span class = "letters">G</span></a><br />
Run Code Online (Sandbox Code Playgroud)

我在这里错过了什么?

Rok*_*jan 10

jsBin演示

<ul id="links">
    <li><a href="#a">Go to a</a></li>
    <li><a href="#b">Go to b</a></li>
</ul>
Run Code Online (Sandbox Code Playgroud)

而且比你文件中的某个地方......

<h2 id="a">Article "a"</h2>
Lorem......
<h2 id="b">Article "b"</h2>
Lorem......
Run Code Online (Sandbox Code Playgroud)

JQ:

$('#links a').click(function( e ){  
    e.preventDefault();
    var targetId = $(this).attr("href");
    var top = $(targetId).offset().top;
    $('html, body').stop().animate({scrollTop: top }, 1500);
});
Run Code Online (Sandbox Code Playgroud)

上面做的是使用检索到的锚href并将其用作jQuery的# (id)选择器.找到ID元素,获取它的顶部offset,最后为页面设置动画.