gpt4 book ai didi

javascript - JS 平滑滚动,滚动到最终/底部 div 的底部而不是顶部

转载 作者:可可西里 更新时间:2023-11-01 13:28:09 26 4
gpt4 key购买 nike

我有一个滚动到同一页面区域的链接。所以页面不会跳来跳去,我添加了一些 JavaScript 平滑滚动(见下文)。

问题是,脚本将页面滚动到目标 div 的顶部。它通过一些缓和来做到这一点,所以当它到达最终的 div 时它会变慢。这很好,但是如果最后一个 div 小于浏览器窗口的高度,它将永远无法滚动到 div 的顶部。它刚好到达页面底部,看起来很破损,因为没有缓动。

我尝试了几种方法使最终的 div 滚动到 div 的底部,但无济于事。任何想法如何做到这一点?

我在这里做了一个问题的 jsfiddle:https://jsfiddle.net/gky7y6gu/2/

$(function() {
$('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 永远不会超过 body 的高度减去窗口的高度。这样 easeOut 总是可见的。

https://jsfiddle.net/gky7y6gu/3/

$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
if (target.length) {
var scrollTo = target.offset().top;
var bodyHeight = $('body').height();
var windowHeight = $(window).height();
if (bodyHeight - windowHeight < scrollTo) {
scrollTo = bodyHeight - windowHeight;
}
$('html,body').animate({
scrollTop: scrollTo
}, 1000);
return false;
}
}
});
});

关于javascript - JS 平滑滚动,滚动到最终/底部 div 的底部而不是顶部,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34426355/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com