要实现页面滑动到哪块,哪块导航栏高亮的效果,可以使用JavaScript和CSS来实现。以下是一个简单的示例:

HTML部分:

<nav>
  <ul>
    <li><a href="#section1">Section 1</a></li>
    <li><a href="#section2">Section 2</a></li>
    <li><a href="#section3">Section 3</a></li>
  </ul>
</nav>

<section id="section1">
  <h2>Section 1</h2>
  <p>This is the content of section 1.</p>
</section>

<section id="section2">
  <h2>Section 2</h2>
  <p>This is the content of section 2.</p>
</section>

<section id="section3">
  <h2>Section 3</h2>
  <p>This is the content of section 3.</p>
</section>

CSS部分:

nav {
  position: fixed;
  top: 0;
  left: 0;
  background-color: #f2f2f2;
  width: 100%;
}

nav ul {
  list-style-type: none;
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: center;
}

nav li {
  margin: 0 10px;
}

nav a {
  text-decoration: none;
  color: #333;
}

nav a.active {
  font-weight: bold;
}

section {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
}

JavaScript部分:

window.addEventListener('scroll', function() {
  var sections = document.querySelectorAll('section');
  var navLinks = document.querySelectorAll('nav a');
  
  sections.forEach(function(section) {
    var rect = section.getBoundingClientRect();
    if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
      navLinks.forEach(function(link) {
        link.classList.remove('active');
        if (link.getAttribute('href') === '#' + section.id) {
          link.classList.add('active');
        }
      });
    }
  });
});

上述代码中,通过监听windowscroll事件来检测页面滚动。当滚动时,遍历所有的section元素,判断其是否在视口范围内。如果在视口范围内,则将对应的导航栏链接添加active类,以实现高亮效果。

注意,示例中的CSS部分仅为简单样式,并非最终样式。您可以根据需要自定义样式。

希望对您有帮助

如何实现页面滑动到哪块哪块导航栏高亮外加示例

原文地址: http://www.cveoy.top/t/topic/iDUv 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录