导航栏根据位置改变标签颜色+点击锚点滑动到指定位置 jQuery+JavaScript
    		       		warning:
    		            这篇文章距离上次修改已过433天,其中的内容可能已经有所变动。
    		        
        		                
                
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>导航栏颜色变化示例</title>
<style>
  body, html {
    margin: 0;
    padding: 0;
    height: 2000px;
  }
  .navbar {
    position: fixed;
    top: 0;
    width: 100%;
    background-color: #333;
    color: white;
    transition: background-color 0.3s;
  }
  .section {
    height: 500px;
    width: 100%;
  }
</style>
</head>
<body>
 
<div class="navbar">Navbar</div>
 
<div class="section" id="section1" style="background-color: #f44336;">Section 1</div>
<div class="section" id="section2" style="background-color: #e91e63;">Section 2</div>
<div class="section" id="section3" style="background-color: #9c27b0;">Section 3</div>
<div class="section" id="section4" style="background-color: #673ab7;">Section 4</div>
 
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(document).ready(function(){
  var navbar = $('.navbar');
  var sections = $('section');
  var navbarBg = ['#f44336', '#e91e63', '#9c27b0', '#673ab7'];
 
  $(window).scroll(function(){
    var currentPosition = $(this).scrollTop();
    for(var i = sections.length - 1; i >= 0; i--){
      var sectionTop = $(sections[i]).offset().top - 200;
      if (currentPosition >= sectionTop) {
        navbar.css('background-color', navbarBg[i]);
        break;
      }
    }
  });
});
</script>
 
</body>
</html>这段代码使用jQuery监听滚动事件,并根据当前视窗的滚动位置与每个section的顶部位置进行比对,从而改变导航栏的背景颜色。每个section都有一个对应的颜色值,当用户滚动到该section时,导航栏的背景颜色会变成对应的颜色。这个例子演示了一个基本的导航栏颜色变化逻辑,可以根据实际需求进行扩展和修改。
评论已关闭