gpt4 book ai didi

javascript - On Scroll 在页面刷新时自动触发

转载 作者:行者123 更新时间:2023-11-28 15:15:39 25 4
gpt4 key购买 nike

我正在页面中间,因为我有一个 anchor 。我还有一个窗口滚动事件:

$(window).scroll(function(){
});

当我刷新页面时,滚动事件会触发。有没有办法在刷新时防止出现这种情况,但在用户滚动时仍然监听滚动事件?

最佳答案

我相信只有当您刷新页面并且页面滚动时,您的滚动代码才会触发。这是因为浏览器会重新加载页面,然后滚动到原始位置。

Arnelle 建议的解决方案效果不佳,因为滚动事件仅在刷新页面时滚动时才会最初触发。

黑客警报

我发现有效的是等待设置滚动处理程序。请小心,我使用的魔数(Magic Number)可能不适用于所有连接。

//Scroll the page and then reload just the iframe (right click, reload frame)


//Timeout of 1 was not reliable, 10 seemed to be where I tested it, but again, this is not very elegant.
//This will not fire initially
setTimeout(function(){
$(window).scroll(function(){
console.log('delayed scroll handler');
});
}, 10);

//This will fire initially when reloading the page and re-establishing the scroll position
$(window).scroll(function(){
console.log('regular scroll handler');
});
div {  
height: 2000px;
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
</div>

是的,我知道我抨击了 Arnelle,说他们在不理解的情况下修补了一个问题,而我在这里建议修补。唯一的区别是我认为我理解了这个问题。

我向OP提出的主要问题是。我编写的大多数滚动处理程序如果多次调用都可以正常工作,那么您的处理程序被额外调用一次有什么问题吗?

关于javascript - On Scroll 在页面刷新时自动触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34095038/

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