jQuery 仅在向下滚动时平滑滚动偏移?
jQuery smooth scrolling offset only on downscroll?
我目前正在做一个网站项目,并试图通过 jQuery 实现平滑滚动功能。
到目前为止,这是我的(有效!)代码:
$(document).ready(function(){
$('a[href*="#"]:not([href="#"])').click(function() {
var displace = 72; /* Vertical offset for scroll */
var target = $(this.hash);
$('html, body').animate({
scrollTop: target.offset().top - displace}, 1000);
return false;
});
});
因为该站点还有一个 header,它在向下滚动时过渡出视口,在向上滚动时过渡到视口中,我需要通过将滚动目标偏移一定量来以某种方式适应它的可见性,因此 displace
变量。
截至目前,无论滚动方向如何,都会从 target.offset().top
中减去 displace
变量。我该如何修改上面的代码,以便它只在向上滚动时被减去?
我想在其中添加一个 if else
语句,大致如下:
var scrollPos = $(window).scrollTop();
if (target.offset().top > scrollPos) { /* On downscroll */
scroll to target
} else { /* On upscroll */
scroll to target - displace
}
有什么建议可以让它发挥作用吗?
非常感谢!
蒂姆
最终使用这个让它工作:
$(document).ready(function(){
$('a[href*="#"]:not([href="#"])').click(function() {
var scrollPos = $(window).scrollTop();
var displace = 72;
var target = $(this.hash);
if (scrollPos > target.offset().top) {
$('html, body').animate({
scrollTop: target.offset().top - displace}, 1000);
return false;
} else {
$('html, body').animate({
scrollTop: target.offset().top}, 1000);
return false;
}
});
});
我目前正在做一个网站项目,并试图通过 jQuery 实现平滑滚动功能。
到目前为止,这是我的(有效!)代码:
$(document).ready(function(){
$('a[href*="#"]:not([href="#"])').click(function() {
var displace = 72; /* Vertical offset for scroll */
var target = $(this.hash);
$('html, body').animate({
scrollTop: target.offset().top - displace}, 1000);
return false;
});
});
因为该站点还有一个 header,它在向下滚动时过渡出视口,在向上滚动时过渡到视口中,我需要通过将滚动目标偏移一定量来以某种方式适应它的可见性,因此 displace
变量。
截至目前,无论滚动方向如何,都会从 target.offset().top
中减去 displace
变量。我该如何修改上面的代码,以便它只在向上滚动时被减去?
我想在其中添加一个 if else
语句,大致如下:
var scrollPos = $(window).scrollTop();
if (target.offset().top > scrollPos) { /* On downscroll */
scroll to target
} else { /* On upscroll */
scroll to target - displace
}
有什么建议可以让它发挥作用吗?
非常感谢!
蒂姆
最终使用这个让它工作:
$(document).ready(function(){
$('a[href*="#"]:not([href="#"])').click(function() {
var scrollPos = $(window).scrollTop();
var displace = 72;
var target = $(this.hash);
if (scrollPos > target.offset().top) {
$('html, body').animate({
scrollTop: target.offset().top - displace}, 1000);
return false;
} else {
$('html, body').animate({
scrollTop: target.offset().top}, 1000);
return false;
}
});
});