window.scroll事件触发两次 [英] window.scroll events triggering twice
问题描述
无论我使用什么方法来检测页面上的滚动,事件都会触发两次.请查看我尝试过的不同方法的代码.
No matter what method I use to detect scrolling on the page the event is triggered twice. Please see the code for the different methods I have tried.
<body onmousewheel="alert('Why are you alerting twice?')">
或
<script src="js/jquery-1.8.3.min.js"></script>
<script>
$(window).scroll(function(){
alert("Why are you alerting twice?");
});
</script>
或
window.onscroll = please_scroll;
function please_scroll() {
alert("Why are you alerting twice?");
}
我什至尝试使用$ .debounce.
I have even tried using $.debounce.
如果有任何用处,我将解释我想做的事情: 当用户向上或向下滚动滚轮时,页面将使滚动动画到下一个全角内容div.我有成功完成菜单onclick的代码,但是我也希望它在用户滚动时发生,本质上是自动协助他们滚动到页面的每个部分.这是我目前用于滚动的功能:
In case it is of any use I will explain what I am trying to do: When the user scrolls the wheel either up or down, the page will animate the scroll to the next full width content div. I have code that is successfully doing this onclick of my menu, but I would also like it to happen as the user scrolls, essentially auto assisting them with scrolling to each part of my page. This is the function I currently have for scrolling:
function scrollTo(id){
// Scroll
$('html,body').animate({scrollTop: $("#"+id).offset().top - 110},'slow',function(){
animation_active = "false";
});
}
推荐答案
许多设备可以触发滚动事件,这些滚动事件似乎再次发生.只需为此使用超时:
many devices can trigger scroll events which appear to happen once more often. simply use a timeout for that:
var timeout;
$(window).scroll(function() {
clearTimeout(timeout);
timeout = setTimeout(function() {
// do your stuff
}, 50);
});
您可以使用数值50,我建议您输入50到150之间的值.
you can play with the value 50, i recommend something between 50 and 150.
这篇关于window.scroll事件触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!