现在有一种本地方法可以做到这一点:
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);});如果您的目标元素没有ID,并且您正在通过ID链接到它
name,请使用以下命令:
$('a[href^="#"]').click(function () { $('html, body').animate({ scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top }, 500); return false;});为了提高性能,您应该缓存该
$('html, body')选择器,以便它不会在 每次 单击定位器时都运行: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;});


