jquery setInterval或scroll
我正在做一个项目,我需要听scroll
事件..我想知道什么是更好的方法..
第一种方法
function scroll() { if ($(window).scrollTop() > 200) { top.fadeIn(); } else { top.fadeOut(); } if (menuVisible) { quickHideMenu(); } }
第二种方法
function scroll() { didScroll = true; } setInterval(function() { if ( didScroll ) { didScroll = false; if ($(window).scrollTop() > 200) { top.fadeIn(); } else { top.fadeOut(); } if (menuVisible) { quickHideMenu(); } } }, 250);
谢谢 :)
都不是。 我刚刚阅读有关JS / jQuery模式的内容。 Window Scroll事件有一个例子: jQuery Window Scroll Pattern
var scrollTimeout; // global for any pending scrollTimeout $(window).scroll(function () { if (scrollTimeout) { // clear the timeout, if one is pending clearTimeout(scrollTimeout); scrollTimeout = null; } scrollTimeout = setTimeout(scrollHandler, 250); }); scrollHandler = function () { // Check your page position if ($(window).scrollTop() > 200) { top.fadeIn(); } else { top.fadeOut(); } if (menuVisible) { quickHideMenu(); } };
最初来自这里: Javascript模式