gpt4 book ai didi

javascript - 多个不同高度的固定导航栏的平滑滚动

转载 作者:行者123 更新时间:2023-11-28 02:32:53 24 4
gpt4 key购买 nike

我有一个固定顶部的导航栏(75 像素高),滚动流畅,非常适合桌面。当我在小屏幕上时,我有一个不同的导航栏(50 像素高度),高度更小,因此 anchor 发送到达正确的位置。

// Smooth Scoll
$('a[href*="#"]')
.not('[href="#"]')
.not('[href="#0"]')
.click(function(event) {
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) {
event.preventDefault();
$('html, body').animate({
scrollTop: target.offset().top -75
}, 1200, function() {
var $target = $(target);
$target.focus();
if ($target.is(":focus")) {
return false;
} else {
$target.attr('tabindex','-1');
$target.focus();
};
});
}
}
});

我希望能够根据单击的导航栏设置 target.offset().top。请不要使用 css 解决方案。

最佳答案

添加屏幕宽度检查并将 75 更改为 50

// Smooth Scoll
$('a[href*="#"]').not('[href="#"]') .not('[href="#0"]').click(function(event) {
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) {
event.preventDefault();
$('html, body').animate({

// change dependant on screen width
if ($(window).width() < 960) { // set in px
scrollTop: target.offset().top -50
} else {
scrollTop: target.offset().top -75
}

}, 1200, function() {
var $target = $(target);
$target.focus();
if ($target.is(":focus")) {
return false;
} else {
$target.attr('tabindex','-1');
$target.focus();
};
});
}
}
});

或者你可以,这可能更好地获得点击时的导航高度

//set nav 
var nav = $('.nav-bar'); // update to your nav class

// Smooth Scoll
$('a[href*="#"]').not('[href="#"]').not('[href="#0"]').click(function(event) {

// get nav height
var NavHeight = nav.height();

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) {
event.preventDefault();
$('html, body').animate({

// minus nav height
scrollTop: target.offset().top - NavHeight

}, 1200, function() {
var $target = $(target);
$target.focus();
if ($target.is(":focus")) {
return false;
} else {
$target.attr('tabindex','-1');
$target.focus();
};
});
}
}
});

关于javascript - 多个不同高度的固定导航栏的平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47605907/

24 4 0