2017-07-19 66 views
1

我搜查了很多帖子並查看了很多答案,並且沒有運氣試過它們。Javascript/jquery,爲什麼我的淡入淡出不起作用?

我得到它與jquery彩色動畫工作,但後來我不得不鏈接另一個圖書館的id喜歡避免。

我試過CSS動畫,我想不出做的工作,因爲當我刪除的CSS類它沒有得到讓淡出效果,有機會..

只有在淡入/淡出效果,犯規發生。背景顏色正確切換。

TL; DR:希望我的頂部導航欄從透明背景變成白色背景,當訪問者從頂部滾動X個數量,然後返回到透明時,當訪問者靠近頁面頂部並具有平滑過渡效果時。

$(document).ready(function(){ 

    $(document).scroll(function(){ 

    if ($(this).scrollTop() > 200) { 

     if ($("#topnav").hasClass('transparent')){ 

     $("#topnav").removeClass('transparent'); 

     $("#topnav").addClass('black').fadeIn(1000); 

     } 

    } else if ($(this).scrollTop() < 200) { 

     if ($('#topnav').hasClass('black')){ 

     $('#topnav').removeClass('black'); 

     $('#topnav').addClass('transparent').fadeIn(1000); 

     } 

    } 
    }); 
}); 

爲什麼不能正常工作?

+0

[背景顏色的jQuery淡出](可能的重複https://stackoverflow.com/questions/2652281/jquery-fade- in-background-color) – abhishekkannojia

+0

從接受的答案有:_「純粹的jQuery沒有功能來動畫顏色。你必須使用jQueryUI或jQuery顏色插件。「_ – abhishekkannojia

回答

1

您可以簡單地使用CSS設置背景色,並使用CSS過渡來實現淡入/淡出效果。

.box { 
    background-color: black; 
    -webkit-transition: background-color 2s; 
    transition: background-color 2s; 
} 

而在Javascript中你可以設置顏色:

if ($(this).scrollTop() > 200) { 
    $("#topnav").css({"background-color", "yellow"}); 
} 

jsfiddle

0

試試這個簡單的例子

在你的CSS文件,

.transparent-background { 
    background-color: transparent; 
    -webkit-transition: background-color 1000ms ease; 
    -ms-transition: background-color 1000ms ease; 
    transition: background-color 1000ms ease; 
} 

.black-background { 
    background-color: black; 
    -webkit-transition: background-color 1000ms ease; 
    -ms-transition: background-color 1000ms ease; 
    transition: background-color 1000ms ease; 
} 

而且在你的js文件只需添加類之前附着透明背景類topNav容器

$(document).ready(function(){ 
    $(document).scroll(function(){ 
    if ($(this).scrollTop() > 200) { 
     $("#topnav").removeClass("transparent-background").addClass('black- 
       background')  
    } else { 
     $("#topnav").removeClass("black- 
       background").addClass('transparent-background') 
    } 
}); 
}); 
相關問題