jquery实现章节目录效果

  本示例实现文章详细内容如果添加了anchor锚点时,在页面右边生成一个不随页面滚动的固定anchor列表,当那些章节锚点显示在浏览器可见视窗内,增加浮动章节列表的锚点获得焦点的样式。

章节的锚点位置注意看示例中的代码,将会取章节容器中的第一个子元素锚点作为章节目录列表内容。

jquery实现章节目录效果

jquery实现章节目录效果源代码

<!DOCTYPE html >
<title>jquery实现章节目录效果</title>
<script src="https://g.csdnimg.cn/??lib/jquery/1.12.4/jquery.min.js"></script>
<style>
body{background-attachment:fixed;background-image:url(about:blank)}/*修正IE6下浮动层闪动*/
#anchor{position:fixed;top:150px;right:0px;border:solid 1px black;}
#anchor.fixie6{position:absolute;top:expression(eval(document.documentElement.scrollTop)+150);}
#anchor a{text-decoration:none;color:blue;}
#anchor a.focus{background:red;color:white;}
</style>
<script>
    if (document.all) document.write('<!--[if lte IE 6]><script type="text/javascript">window.fixIE6= true<\/script><![endif]-->');//增加是否为IE6的判断
    window.onload = function () {
        var strict = document.compatMode == 'CSS1Compat', contents = $('div>a[name]:first-child'), anchors, s = [];
        contents.each(function () { s[s.length] = '<a href="#' + this.name + '">' + this.name + '</a>'; });
        anchors = $('<div id="anchor"' + (window.fixIE6 ? ' class="fixie6"' : '') + '>' + s.join('<br>') + '</div>').appendTo(document.body).find('a'); //添加文章的章节目录
        contents = contents.parent(); //更新章节锚点为内容节点
        //计算内容节点的上端点和下端点
        contents.each(function () { var o = $(this); o.data('top-bottom', { top: o.offset().top, bottom: o.offset().top + o.height() }); });
        $(window).scroll(function () {
            var viewTop = Math.max(document.body.scrollTop, document.documentElement.scrollTop); //可见高度顶部
            var viewBottom = document[strict ? 'documentElement' : 'body'].clientHeight + viewTop; //可见高度底部
            contents.each(function (index, el) {
                var tb = $(this).data('top-bottom');
                if ((tb.top > viewTop && tb.top < viewBottom) || (tb.bottom > viewTop && tb.bottom < viewBottom) || (tb.top < viewTop && tb.bottom > viewBottom))
                    anchors.eq(index).addClass('focus');
                else
                    anchors.eq(index).removeClass('focus');
            });
        }).trigger('scroll');
        $('#anchor a').click(function () {
            $(document.documentElement).animate({ scrollTop: $(this.hash).offset().top });
            return false
        });
    };
</script>
<div style="height:800px"><a name="anchor1" id="anchor1">anchor1</a></div>
<div style="height:800px"><a name="anchor2" id="anchor2">anchor2</a></div>
<div style="height:800px"><a name="anchor3" id="anchor3">anchor3</a></div>
<div style="height:800px"><a name="anchor4" id="anchor4">anchor4</a></div>

 

加支付宝好友偷能量挖...


原创文章,转载请注明出处:jquery实现章节目录效果

评论(0)Web开发网
阅读(1571)喜欢(0)JavaScript/Ajax开发技巧