我的页面上有几个超链接。用户在访问我的帮助部分时将阅读的常见问题解答。
使用 anchor 链接,我可以使页面滚动到 anchor 并引导用户到那里。
有没有办法让滚动流畅?
但请注意,他使用的是自定义 JavaScript 库。也许 jQuery 提供了类似的东西?
最佳答案
2018 年 4 月更新:现在有 a native way to do this :
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
这目前仅在最前沿的浏览器中受支持。
对于较旧的浏览器支持,您可以使用以下 jQuery 技术:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
这是 fiddle :http://jsfiddle.net/9SDLw/
如果您的目标元素没有 ID,并且您通过它的 name
链接到它,请使用:
$('a[href^="#"]').click(function () {
$('html, body').animate({
scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top
}, 500);
return false;
});
为了提高性能,您应该缓存 $('html, body')
选择器,这样它就不会在每次单击 anchor 时运行:
var $root = $('html, body');
$('a[href^="#"]').click(function () {
$root.animate({
scrollTop: $( $.attr(this, 'href') ).offset().top
}, 500);
return false;
});
如果您希望更新 URL,请在 animate
回调中进行:
var $root = $('html, body');
$('a[href^="#"]').click(function() {
var href = $.attr(this, 'href');
$root.animate({
scrollTop: $(href).offset().top
}, 500, function () {
window.location.hash = href;
});
return false;
});
关于javascript - 单击 anchor 链接时平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7717527/