2013-01-10 121 views
6

我正在尝试以下jQuery代码。
当我滚动向上或向下我想fadeOut一个div和当滚动已停止fadeIn相同的div。jQuery滚动事件

什么我是这样的:

$(document).ready(function(){ 
    $(window).scroll(function(e){ 
    $('#search_tab').fadeOut('slow'); 
    }); 
}); 

我知道,这将fadeOut div时滚动已经开始,但关键是要消除它回来一次我停止滚动。现在

,我已经看到了这一点(但还是不太我想要的)

//Firefox 
$('#elem').bind('DOMMouseScroll', function(e){ 
    if(e.detail > 0) { 
     //scroll down 
     console.log('Down'); 
    }else { 
     //scroll up 
     console.log('Up'); 
    } 

    //prevent page fom scrolling 
    return false; 
}); 

上述功能将无法在所有的如下工作:

$(window).bind('DOMMouseScroll', function(e){ 
    if(e.detail > 0) { 
     //scroll down 
     $('#search_tab').fadeOut('slow'); 
    }else { 
     //scroll up 
     $('#search_tab').fadeOut('slow'); 
    } 

    //prevent page fom scrolling 
    return false; 
}); 

回答

4

没有scrollstop监听事件,但您可以使用012模拟一个setTimeout()函数,然后每次页面滚动时清除timer。这里是一个样本fiddle

var timer;  
$(window).scroll(function(e){ 
     clearTimeout(timer); 
     $('#search_tab').fadeOut('slow'); 
     timer = setTimeout(checkStop,150); 
}); 

function checkStop(){ 
    $('#search_tab').fadeIn('slow'); 
} 
+0

它也可以,thx :) – user1965451

2

您可以检查每一帧:

// shim for frame listener 
window.requestAnimFrame = (function(){ 
     return window.requestAnimationFrame  || 
       window.webkitRequestAnimationFrame || 
       window.mozRequestAnimationFrame || 
       window.oRequestAnimationFrame  || 
       window.msRequestAnimationFrame  || 
       function(callback){ 
       window.setTimeout(callback, 1000/60); 
       }; 
    })(); 

    // on every frame, call render() 
    (function animloop(){ 
     requestAnimFrame(animloop); 
     render(); 
    })(); 


var lastScroll = 0, isScrolling = false; 
function render(){ 
    var thisScroll = $(window).scrollTop(); 
    if(lastScroll !== thisScroll){ 
    if(!isScrolling){ 
     // scrolling has started, fade out div 
     $('#search_tab').stop().fadeOut('slow'); 
    } 
    isScrolling = true; 
    }else{ 
    if(isScrolling){ 
     // scrolling has stopped, fade in div 
     $('#search_tab').stop().fadeIn('slow'); 
    } 
    isScrolling = false; 
    } 
    lastScroll = thisScroll; 
} 
+0

很好,只是我在找什么 – user1965451