im使用以下代码在我的网站上添加平滑滚动。因为我有一个粘性标题ID喜欢用200px
来抵消这一点$('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;
}
}
});
尝试在scrolltop动画中添加或删除一个值
$('a[href*="#"]:not([href="#"])').click(function() {
var offset = -200; // <-- change the value here
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 + offset
}, 1000);
return false;
}
}
});
一个更简单的示例,没有哈希是:
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top + -200
}, 1000);
});