alternative to (window).scroll [duplicate]

早过忘川 提交于 2020-01-06 07:43:12

问题


Possible Duplicate:
ScrollTop really jerky in Chrome

I'm using the following code to get a back to top button and a navigation to fade in once the user scrolls. The problem is its triggering every time you scroll, therefore causing the scrolling to be really jerky. Is there an alternate way to do this, which would maybe trigger the function only once?

    $(function () {
    $(window).scroll(function () {
        if ($(this).scrollTop() > 600) {
            $('#backToTop, #navigation').fadeIn();
        } else {
            $('#backToTop, #navigation').fadeOut();
        }
    });
    }); 

   });

回答1:


Maybe set a timeout...

function scrollit(){  
    if ($(this).scrollTop() > 600) {
    $('#backToTop').fadeIn();
    } else {
    $('#backToTop').fadeOut();
    }
     }

var timer;

$(window).scroll(function () {

window.clearTimeout(timer);
timer = window.setTimeout(function(){ scrollit(); }, 2000);

    }); 



回答2:


You could implement Ben Alman's jQuery throttle or debounce plugin. Basically this limits your functions to be run only a certain amount of times. The difference between the two is explained on the website:

Well, to put it simply: while throttling limits the execution of a function to no more than once every delay milliseconds, debouncing guarantees that the function will only ever be executed a single time (given a specified threshhold).



来源:https://stackoverflow.com/questions/13224207/alternative-to-window-scroll

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