在多个部分中滚动导航到h2

Scroll-navigation to h2 in multiple sections

本文关键字:导航 h2 滚动 个部      更新时间:2023-09-26

我要开发一种在线图书。
在每一章(具有特定id的部分)中,我想在中的每个h2中添加一个自动生成的带滚动导航的边栏。侧边栏当然应该在每个包含单独h2的部分中生成,并链接到它们。

我试过这个scrollnav插件。实际上,它的工作,但问题是,它不能生成正确的链接,因为它不允许工作在多个部分(在section2中,它实际上链接到section1等)。

谁有更好的解决方案?

Obs:这是一本很长的电子书(13-15章,每个章节有10-12个"小章节")。因此,自动生成的id到h2(或其他解决方案)将首选:-)

HTML:

<section id="1">
<h2>Sub-chapter 1</h2>
<h2>Sub-chapter 2</h2>
<h2>Sub-chapter 3</h2>
</section>
<section id="2">
<h2>Sub-chapter 1</h2>
<h2>Sub-chapter 2</h2>
<h2>Sub-chapter 3</h2>
</section>
<section id="3">
<h2>Sub-chapter 1</h2>
<h2>Sub-chapter 2</h2>
<h2>Sub-chapter 3</h2>
</section>

也许我应该说:我还是javascript新手

// Document ready
jQuery(document).ready(function(){
    jQuery('section').each(function(){
        var html = '<ul>';
        var id = jQuery(this).attr('id');
        var i = 1;
        jQuery(this).children('h2').each(function(){
            jQuery(this).attr('id', id + '-' + i);
            html += '<li><a href="#' + jQuery(this).attr('id') + '">' + jQuery(this).text() + '</a></li>';
            i++;
        });
        html += '</ul>';
        jQuery(this).prepend(html);
    });
});

http://jsfiddle.net/sh9xzc2c/