当用户点击href以"#"开头的链接时,我正在使用以下代码来平滑移动
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
Run Code Online (Sandbox Code Playgroud)
我需要在scrollTop值上添加大约40px,因此停止点可以覆盖内容.我将代码修改为此,但它似乎没有这样做(注意代码末尾的+40):
$(document).ready(function(){
$('a[href^="#"]').on('click',function (e) {
e.preventDefault();
var target = this.hash,
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top + 40
}, 900, 'swing', function () {
window.location.hash = target;
});
});
});
Run Code Online (Sandbox Code Playgroud)
Pex*_*sol 18
我知道一个迟到的答案,但有人寻求解决方案可以试试这个.
通过添加.top +( - 40)就可以了
$('html, body').stop().animate({
'scrollTop': $target.offset().top + (-40)
}, 900, 'swing', function () {
window.location.hash = target;
});
Run Code Online (Sandbox Code Playgroud)
+40您实际想要的偏移量不起作用-40,因为一旦动画完成,浏览器就会执行默认反应,即使用id,因为一旦动画完成,浏览器就会执行默认反应,即转到您要传递给的window.location.hash
您可以删除该行或将以下 css 添加到滚动到的元素中。
padding-top: 40px;
margin-top: -40px;
Run Code Online (Sandbox Code Playgroud)
参见小提琴