作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在页面中间,因为我有一个 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/
我是一名优秀的程序员,十分优秀!