jQuery 如何在页面滚动时淡入/淡出 div?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9438894/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:48:58  来源:igfitidea点击:

How do I fade a div in/out on page scroll?

jqueryscrollfadeshow-hide

提问by egr103

Here is the jsfiddle: http://jsfiddle.net/NKgG9/

这是 jsfiddle:http: //jsfiddle.net/NKgG9/

I'm basically wanting those pink boxes to be on show on page load as normal but as soon as a user scrolls down the page I want them to fade out and disappear. When the user scrolls back up to their position or the top of the browser window I want those pink boxes to fade back in again. I'm useless with JS so good do with some help on how to do this.

我基本上希望那些粉红色的框像往常一样在页面加载时显示,但是一旦用户向下滚动页面,我希望它们淡出并消失。当用户向上滚动到他们的位置或浏览器窗口的顶部时,我希望那些粉红色的框再次淡入。我对 JS 没用,所以在如何做到这一点的帮助下做得很好。

All help appreciated.

所有帮助表示赞赏。

回答by Cheery

Very simple example: http://jsfiddle.net/a4FM9/2/

非常简单的例子:http: //jsfiddle.net/a4FM9/2/

var divs = $('.social, .title');
$(window).scroll(function(){
   if($(window).scrollTop() <10 ){
         divs.stop(true,true).fadeIn("fast");
   } else {
         divs.stop(true,true).fadeOut("fast");
   }
});?

回答by Andre Loker

Like this? http://jsfiddle.net/NKgG9/6/

像这样?http://jsfiddle.net/NKgG9/6/

$(function(){ 
    var targets = $(".title, .social");
    if($(window).scrollTop() > 10){
      targets.hide();
    }
    $(window).scroll(function(){
        var pos = $(window).scrollTop();
        if(pos > 10){
            targets.stop(true, true).fadeOut("fast" );
        } else {
            targets.stop(true, true).fadeIn("fast");
        }
    });

});

The basic idea: subscribe to the scroll event. If the scroll position moves past a certain point, start the fade out and likewise if the user scrolls up fade in. Some important details: keep track if you're already fading in/out (variable shown) and stop any ongoing fade if you start a new fade.

基本思想:订阅滚动事件。如果滚动位置移动超过某个点,则开始淡出,如果用户向上滚动淡入,则开始淡出。一些重要的细节:如果您已经淡入/淡出(显示变量),请跟踪并停止任何正在进行的淡入,如果您开始新的淡入淡出。