滚动时更改导航栏的背景颜色

Med*_*eds 2 javascript css jquery

我想在滚动期间激活时更改background-color导航栏的position: sticky

background-color当滚动到达时,我设法更改了导航栏的 ,但我想为其设置动画以使这种变化更加渐进。

这是我尝试过的:

window.onscroll = function() {myFunction()};

var navbar = document.getElementById("menu_navbar");

var rect = navbar.getBoundingClientRect();

function myFunction() {
  if (window.pageYOffset >= rect.top) {
     $( "#menu_navbar" ).animate({
        "background-color": "rgba(255, 229, 57, 0.8)"
     }, 1000);
  } 
  else {
     navbar.style.backgroundColor = 'transparent';
  }
}
Run Code Online (Sandbox Code Playgroud)

T. *_*ort 5

您可以简单地声明一个过渡样式:

transition: background-color .5s ease;

然后,每当您更改背景颜色时,它都会有动画效果。