QaQlinks / Html 实例 / 左侧导航随右侧内容滚动 131 个条目

左侧导航随右侧内容滚动

Html 实例 #33 更新 2023-10-12

纯前端实现的锚点导航:右侧正文滚动时,左侧目录自动高亮当前所在章节,点击也能跳转。不依赖任何框架,适合长文档、服务条款、帮助中心这类内容,读者不用来回滚动找位置。



<!DOCTYPE html>
<html>
<head>
    <style>
        /* 标题导航样式 */
        .nav {
            position: fixed;
            width: 25%;
            height: 100%;
            overflow: auto;
        }

        .nav a {
            display: block;
            padding: 10px;
            color: #000;
            text-decoration: none;
        }

        .nav a:hover {
            background-color: #ccc;
        }

        /* 文章内容样式 */
        .content {
            margin-left: 25%; /* 左边的导航栏宽度 */
            height: 300px;
            overflow: auto;
        }

        .content p {
            padding: 10px;
            line-height: 1.5;
        }

        /* 高亮样式 */
        .active {
            background-color: #ccc;
        }
    </style>
</head>
<body>
    <div class="nav">
        <a href="#section1" target="_blank"  rel="nofollow" >标题1</a>
        <a href="#section2" target="_blank"  rel="nofollow" >标题2</a>
        <a href="#section3" target="_blank"  rel="nofollow" >标题3</a>
        <a href="#section4" target="_blank"  rel="nofollow" >标题4</a>
        <a href="#section5" target="_blank"  rel="nofollow" >标题5</a>
    </div>

    <div class="content">
        <p id="section1">这是标题1的内容。</p>
        <p id="section2">这是标题2的内容。</p>
        <p id="section3">这是标题3的内容。</p>
        <p id="section4">这是标题4的内容。</p>
        <p id="section5">这是标题5的内容。</p>
    </div>

    <script>
        // 获取标题元素和内容元素
        var navLinks = document.getElementsByTagName('a');
        var contentSections = document.getElementsByTagName('p');

        // 监听滚动事件
        window.addEventListener('scroll', function() {
            var currentSection = '';

            // 遍历内容元素,找到当前可见的部分
            for (var i = 0; i < contentSections.length; i++) {
                var rect = contentSections[i].getBoundingClientRect();
                if (rect.top >= 0 && rect.bottom <= window.innerHeight) {
                    currentSection = contentSections[i].id;
                }
            }

            // 移除所有标题的高亮样式
            for (var j = 0; j < navLinks.length; j++) {
                navLinks[j].classList.remove('active');
            }

            // 给当前可见的标题添加高亮样式
            if (currentSection !== '') {
                var activeLink = document.querySelector('a[href="#' + currentSection + '"]');
                activeLink.classList.add('active');
            }
        });
    </script>
</body>
</html>


点击统计

最近 30 天 · 单日最高 4 · 数据刚开始累积
4总点击
0今日
4近 7 天
0.1日均
0123411-26 · 4 次10-2911-0511-1311-20今天

评论

0

还没有评论,来说两句。

发表评论

邮箱不会被公开。带 * 的为必填项。

记录信息

分类
Html 实例
类型
HTML 实例
使用
附完整代码,可复制到本地直接运行
更新
2023-10-12
点击
4 次
编号
#33