jQuery 实现支持分级标题标签的文章目录

背景

首个版本

www.ouorz.com/366

修改意见

鉴于单个 H 标签设置比较麻烦纠结,而且有主题用户反馈,索性改成可以分级的啦


代码

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')
}
复制代码

↑ JavaScript 代码


批注

$(“:header”) 可以获取标题标签(Hx)

prop(“tagName”).replace(‘H’, ”) 可以获取到标签级别

转载于:https://juejin.im/post/5cbc3eaae51d456e747c5347

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值