【问题标题】:Smooth Scrolling With Anchor Links使用锚链接平滑滚动
【发布时间】:2016-11-03 06:53:11
【问题描述】:
我想知道是否有人有一些简单的代码可以获取我的锚链接并在单击时平滑滚动到页面的该部分。现在,每当我点击我的链接时,它基本上都会传送到网页的那个部分,没有任何平滑滚动。任何帮助将不胜感激,谢谢!
附:我在 CodePen 中这样做
【问题讨论】:
标签:
html
css
smooth-scrolling
codepen
【解决方案1】:
您可以按照Chris Coyier's article 和随附的codepen 尝试这个jQuery 脚本:
$(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
}, 1000);
return false;
}
}
});
});
请注意 Chris 的 codepen 中的锚标记 href 是如何引用相关的 h2 id 的。
发布您的代码笔,我们可以看看。