window.scroll events triggering twice

耗尽温柔 提交于 2019-11-30 14:00:14

问题


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?')">

or

<script src="js/jquery-1.8.3.min.js"></script>
<script>
$(window).scroll(function(){
    alert("Why are you alerting twice?");
});
</script>

or

window.onscroll = please_scroll;

function please_scroll() {
      alert("Why are you alerting twice?");
    }

I have even tried using $.debounce.

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";
  });
}

回答1:


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);
});

you can play with the value 50, i recommend something between 50 and 150.



来源:https://stackoverflow.com/questions/22018348/window-scroll-events-triggering-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!