滚动时如何使导航栏上的动画平滑滑动?

时间:2020-08-25 22:11:36

标签: html jquery css animation

因此,我想制作一个导航栏动画。在我的网站上,我的导航栏高度为80px,位于position:relative中。向下滚动超过80像素后,我想制作一个向下滑动的动画,然后将导航栏设置为position:fixed

以下是一段简短的代码,可以帮助您更好地了解自己的操作:

$(document).ready(function(){
  $(window).scroll(function(){
    var scroll = $(window).scrollTop();
      if (scroll > 80) {
        $(".black").css("position" , "fixed");
      $(".black").css("transition", "position 6s ease");
      }

      else{
          $(".black").css("position" , "absolute");     
      }
  })
})
body{
  margin:0;
  padding:0;
  height:1000px;
}
.black{
  position:relative;
  top:0;
  background:#333;
  width:100%;
  height:50px;
  
}
.black ul{
  list-style-type:none;
  padding:0;
  text-align:center;
}

.black ul li{
  display:inline-block;
  width:100px;
  color:white;
}

.blue{
  position:fixed;
  top:0;
  background:blue;
  width:100%;
  height:50px;
}
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<body>
<div class="black">
  <ul>
    <li>link</li>
    <li>link</li>
    <li>link</li>
    <li>link</li>
  </ul>
</div>
</body>
</html>

如您所见,当我向下滚动超过80px时,导航栏显示得非常快,动画和延迟为零。我试图增加动画的持续时间,并且有点延迟,但是由于某种原因它没有起作用。 因此,当我向下滚动超过80px并将位置更改为“固定”后,我想制作一个向下导航栏的动画,因此向下滚动后,导航栏将始终位于屏幕顶部。

现在,这是我要制作动画的一个很好的例子(从w3schools复制):

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

function scrollFunction() {
  if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
    document.getElementById("navbar").style.top = "0";
  } else {
    document.getElementById("navbar").style.top = "-50px";
  }
}
body {
  margin: 0;
  background-color: #f1f1f1;
  font-family: Arial, Helvetica, sans-serif;
}

#navbar {
  background-color: #333;
  position: fixed;
  top: -50px;
  width: 100%;
  display: block;
  transition: top 0.4s;
}

#navbar a {
  float: left;
  display: block;
  color: #f2f2f2;
  text-align: center;
  padding: 15px;
  text-decoration: none;
  font-size: 17px;
}

#navbar a:hover {
  background-color: #ddd;
  color: black;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<div id="navbar">
  <a href="#home">Home</a>
  <a href="#news">News</a>
  <a href="#contact">Contact</a>
</div>

<div style="padding:15px 15px 2500px;font-size:30px">
  <p><b>This example demonstrates how to slide down a navbar when the user starts to scroll the page.</b></p>
</div>
</body>
</html>

非常感谢任何可以帮助我的人,因为我对如何制作此动画不太了解。对不起,英语不好,希望您能理解一切都很好。

0 个答案:

没有答案