滚动导航

 

下面是效果图

ezgif-8ca4526462c724

下面是实现代码

 

<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8" />
    <title>滚动导航 Demo</title>
    <style>
        body {
            margin: 0;
            font-family: sans-serif;
            scroll-behavior: smooth;
            /* 平滑滚动 */
        }

        /* 顶部导航栏 */
        .navbar {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            background: #fff;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: center;
            gap: 20px;
            padding: 10px 0;
            z-index: 1000;
        }

        .navbar a {
            color: #555;
            text-decoration: none;
            padding: 6px 10px;
            border-radius: 4px;
        }

        .navbar a.active {
            color: #fff;
            background: #409eff;
        }

        /* 内容区 */
        section {
            height: 100vh;
            padding-top: 60px;
            /* 避免被导航栏遮挡 */
            box-sizing: border-box;
        }

        section:nth-child(odd) {
            background: #f6f6f6;
        }

        section:nth-child(even) {
            background: #e8f1ff;
        }
    </style>
</head>

<body>
    <!-- 顶部导航栏 -->
    <div class="navbar" id="navbar">
        <a href="#s1">首页</a>
        <a href="#s2">功能</a>
        <a href="#s3">关于</a>
    </div>

    <!-- 页面内容 -->
    <section id="s1">
        <h2>首页</h2>
    </section>
    <section id="s2">
        <h2>功能介绍</h2>
    </section>
    <section id="s3">
        <h2>关于我们</h2>
    </section>

    <script>
        const links = document.querySelectorAll('.navbar a');
        const sections = Array.from(links).map(a => document.querySelector(a.getAttribute('href')));

        const observer = new IntersectionObserver((entries) => {
            entries.forEach(entry => {
                if (entry.isIntersecting) {
                    links.forEach(link => link.classList.toggle('active', link.getAttribute('href').slice(1) === entry.target.id));
                }
            });
        }, { threshold: 0.6 }); // 进入视口 60% 时高亮

        sections.forEach(s => observer.observe(s));
    </script>
</body>

</html>

 

posted @ 2025-10-08 13:40  unique-yb  阅读(34)  评论(0)    收藏  举报