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

标签 javascript jquery

我正在页面中间,因为我有一个 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/

相关文章:

javascript - 在 Javascript 中将任何类型的字符串更改为标题大小写

javascript - jquery 将点击事件传递给 onclick 属性

javascript - JQuery:获取跨度内的对象

javascript - 使用 ng-annotate-loader 和 babel-loader 进行 js 的 webpack 配置

javascript - 在 Jquery/Ajax 导航 Wordpress 上更新 <head> balise

javascript - jQuery UI 可拖动位于其他元素后面

javascript - knockout HTML 绑定(bind)和 HTML 字符串长度

javascript - 如何实现页面之间的动画

jquery - 是否可以使用 'and' 或 'or' 来加入多个选择器? (JQuery)

javascript - 请求 JSONP 时的 text/html 输出