<html><head><title>jquery实现章节目录效果</title> <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.4.2.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'); }); }; </script> </head><body><div style="height:800px"><a name="anchor1">anchor1</a></div> <div style="height:800px"><a name="anchor2">anchor2</a></div> <div style="height:800px"><a name="anchor3">anchor3</a></div> <div style="height:800px"><a name="anchor4">anchor4</a></div><div id="anchor"><a href="#anchor1" class="focus">anchor1</a><br><a href="#anchor2" class="focus">anchor2</a><br><a href="#anchor3" class="">anchor3</a><br><a href="#anchor4" class="">anchor4</a></div></body></html>