jQuery 實現支持分級標題標籤的文章目錄

背景

首個版本

https://www.ouorz.com/366javascript

修改意見

鑑於單個 H 標籤設置比較麻煩糾結,並且有主題用戶反饋,索性改爲能夠分級的啦css

代碼

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 代碼html

批註

$(「:header」) 能夠獲取標題標籤(Hx)java

prop(「tagName」).replace(‘H’, 」) 能夠獲取到標籤級別c++

相關文章
相關標籤/搜索