簡體   English   中英

如何使用jQuery在滾動畫面中淡入淡出圖像?

[英]How do I get an image to fade in and out on a scroll using jQuery?

這個問題似乎很簡單,但我似乎無法使淡入淡出效果正常工作,請查看小提琴以查看代碼,您會注意到,圖像僅在向上滾動時逐漸淡入,而向下滾動時不會淡出,為什么會這樣? 我認為我不完全了解自己編寫的代碼,希望能得到一些幫助。

這是jQuery代碼

var divs = $('.banner');
$(window).scroll(function(){
if($(window).scrollTop()<10){
     divs.stop(true, true).fadeIn(5000);
} else {
     divs.stop(true, true).fadeOut(5000);
 }
});

先感謝您!

http://jsfiddle.net/a4FM9/809/

演示

var divs = $('.banner');
$(window).scroll(function(){
   if($(window).scrollTop()<10){
         divs.stop(true, true).hide().fadeIn(5000); //added hide before fadeIn
   } else {
         divs.stop(true, true).show().fadeOut(5000); //added show before fadeOut
   }
});

很簡單,您只需刪除.stop(true, true) ,它就會在兩個方向上消失:

工作實例

var divs = $('.banner');
$(window).scroll(function(){
   if($(window).scrollTop()<=10){
         divs.fadeIn(5000);
   } else {
         divs.fadeOut(5000);
   }
});

如果要在滾動停止后進行淡入淡出,可以使用超時功能,如下所示:

工作示例2

$(window).scroll(function () {
    clearTimeout($.data(this, 'scrollTimer'));
    $.data(this, 'scrollTimer', setTimeout(function () {
        var divs = $('.banner');
        if ($(window).scrollTop() <= 200) {
            divs.fadeIn(5000);
        } else {
            divs.fadeOut(5000);
        }
    }, 1000)); //timeout set to 1 second
});

有關此超時功能的更多信息,請參見: yckart的超時功能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM