gpt4 book ai didi

javascript - jQuery 使用 .scroll(handler) 滚动到一个元素

转载 作者:行者123 更新时间:2023-12-02 14:42:51 24 4
gpt4 key购买 nike

在从页面顶部向下滚动一定距离后,我尝试滚动到页面上的目标元素。因此滚动到元素是由 .scroll() 事件触发的。我已经能够使用以下代码来做到这一点:

$( document ).scroll( function( e ) {
if ( $(document).scrollTop() > 250 ) {
$('html, body').animate({
scrollTop: $("#cy-hero-image").offset().top
}, 650);
}
});

但是问题是,一旦滚动触发此事件,页面就会停留在该滚动位置。如何编写这段代码,使其在从页面顶部滚动时仅跳转到该页面位置一次?

这是JSFiddle到目前为止我所拥有的。

最佳答案

您可以添加一个变量来检查它是否来自顶部。

var startsFrom = 0;
$(document).scroll(function(e) {
if($(document).scrollTop() == 0) //you can adjust it to match whatever you want
startsFrom = 0;
if ($(document).scrollTop() > 250 && startsFrom == 0) {
startsFrom = $(document).scrollTop();
$('html, body').animate({
scrollTop: $("#targeted-element").offset().top
}, 650);
}
});

https://jsfiddle.net/pdyu3f5b/14/

关于javascript - jQuery 使用 .scroll(handler) 滚动到一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36872402/

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