用 jQuery 写一个获取文章目录的功能

Posted ·1263 Views·1290 Words

思路

jQuery 有一个 each() 函数,可以获取每一个对应元素。比如博客主题文章中 .article-index h3 就是我一般喜欢作为标题的元素,于是尝试使用它来做一个文章目录功能。初步的做法是讲每一次 each() 函数获取到的 h3 标题的 offset().top 值存入一个数组,在滑动时从第二个下标开始将滑动过的高度与当前 h3 标题高度做对比,大于则跳转至下一个数组值并改变目录指示的样式,小于则跳转至上一个数组值。

 

代码

var count_ti = count_in = count_ar = count_sc = count_hr = count_e = 1;
var offset = new Array;
$('.article-content h3').each(function () { //each获取h3内容
    $('#article-index').html($('#article-index').html() + '<li id="ti' + (count_ti++) +
        '"><a onclick="$(\'body\').animate({ scrollTop: $(\'#in' + (count_hr++) +
        '\').offset().top - 100 }, 500);"><i class="czs-circle-l"></i>  ' + $(this).eq(0).html() +
        '</a></li>');
    $(this).eq(0).attr('id', 'in' + (count_in++)); //h3添加id
    offset[0] = 0;
    offset[count_ar++] = $(this).eq(0).offset().top; //h3位置存入数组
    count_e++
});

if (count_e !== 1) { //若存在h3标签

    $(window).scroll(function () { //滑动窗口时
        var scroH = $(this).scrollTop() + 130;
        var navH = offset[count_sc]; //从1开始获取当前h3位置
        var navH_prev = offset[count_sc - 1]; //获取上一个h3位置(以备回滑)
        if (scroH >= navH) { //滑过当前h3位置
            $('#ti' + (count_sc - 1)).attr('class', '');
            $('#ti' + count_sc).attr('class', 'active');
            count_sc++; //调至下一个h3位置
        }
        if (scroH <= navH_prev) { //滑回上一个h3位置,调至上一个h3位置
            $('#ti' + (count_sc - 2)).attr('class', 'active');
            count_sc--;
            $('#ti' + count_sc).attr('class', '');
        }
    });

} else {
    $('.index-div').css('display', 'none')
}

 

暂时好像没发现什么 Bug ???

再下一级的目录标题的话也可以在 each() 函数中继续执行 each() 函数来获取其他元素

 

后记

将会加入 Tony 主题 v4 版本,并且支持后台设置标题对应的标签 🙂

Comments

Leave a comment to join the discussion