滚动到带链接的页面部分(示例)
学以致用
・1 分钟阅读
随着单页面的网站出现,使用滚动作为一种导航长页面的方法变得越来越流行,使用这个小巧的JS jQuery代码,可以轻松地在导航元素中设置链接,滚动到页面的适当部分,如果你希望在JS不存在时使它降级,请向页面添加锚标记。
Coffeescript:
$(" nav" ).find(" a" ).click (e) ->
e.preventDefault()
section = $(this).attr" href"
$(" html, body" ).animate
scrollTop: $(section).offset().top
或JS:
$(" nav" ).find(" a" ).click(function(e) {
e.preventDefault();
var section = $(this).attr(" href" );
$(" html, body" ).animate({
scrollTop: $(section).offset().top
});
});
和一些示例html
<nav>
<a href= "#welcome"> Welcome</a>
<a href= "#about"> About</a>
<a href= "#section3"> Section 3</a>
</nav>
<div id= "welcome"> Welcome to this website</div>
<div id= "about"> About this website, and such</div>
<div id= "section3"> The third section</div>