不幸的是,没有直接的方式可以说明这一点。
我想说的是,如果您可以重新设计应用程序以使其不依赖于这种类型的流程,那就去吧。
如果没有,我可以想到的解决方法是跟踪用户启动的滚动并检查滚动是否由浏览器或用户触发。
这是我整理好的一个示例(jQuery历史记录有问题的浏览器除外)。
您需要在本地运行此程序,以便能够对其进行全面测试(jsFiddle / jsbin不适用于iFrame内容)。
这是我验证的测试用例:
- 页面加载-
userScroll是false
- 使用鼠标/键盘滚动-
userScroll变为true
- 单击链接跳至页面底部-
userScroll变为false
- 单击后退/前进-
userScroll变为false;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<script src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
<script type="text/javascript" src="https://raw.github.com/tkyk/jquery-history-plugin/master/jquery.history.js"></script>
</head>
<body>
<span> hello there </span><br/>
<a href="#bottom"> click here to go down </a>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>
<a name="bottom"> just sitting </a>
</body>
<script type="text/javascript">
var userScroll = false;
function mouseEvent(e) {
userScroll = true;
}
$(function() {
$.history.init(function(hash){
userScroll = false;
});
$(document).keydown(function(e) {
if(e.which == 33
|| e.which == 34
|| e.which == 32
|| e.which == 38
|| e.which == 40
|| (e.ctrlKey && e.which == 36)
|| (e.ctrlKey && e.which == 35)
) {
userScroll = true;
}
});
if(window.addEventListener) {
document.addEventListener('DOMMouseScroll', mouseEvent, false);
}
document.onmousewheel = mouseEvent;
$('a[href*=#]').click(function() {
userScroll = false;
});
$(document).scroll( function(){
console.log('Scroll initiated by ' + (userScroll == true ? "user" : "browser"));
});
});
</script>
</html>
笔记:
- 当用户用鼠标拖动滚动条时,这不会跟踪滚动。可以添加一些其他代码,我将其留给您作为练习。
event.keyCodes 可能因操作系统而异,因此您可能必须适当地进行更改。
希望这可以帮助!