我想创建一个类似于JavaScript Gardens的内容表。他们如何确定哪个部分当前处于活动状态?您是否有任何推荐的JavaScript库可以解决此问题?
编辑:所以我要求的是如何在用户滚动时知道屏幕上哪个部分当前处于活动状态,以便我可以在内容列表中突出显示该部分。
答案 0 :(得分:2)
您可以检测元素何时进入浏览器的视口,然后突出显示相应的菜单项。
通过在Firefox中使用Firebug,您可以看到他们使用窗口的scrollTop
属性来了解用户正在查看的内容。
highlight: function () {
// get the scroll height
var scroll = this.page.window.scrollTop(),
articleID = this.names[this.names.length - 1].id;
// while our item are above the viewport, we enumerate
for (var i = 0, l = this.names.length; i < l; i++) {
if (this.names[i].offset > scroll) {
articleID = this.names[i - 1].id;
break;
}
}
// we've got the content to highlight, let's add classes and expand menu-entries
var sectionID = articleID.split('.')[0],
page = this.page,
nav = page.nav;
if (sectionID !== page.section) {
nav.filter('.nav_' + page.section).removeClass('active');
nav.filter('.nav_' + sectionID).addClass('active');
this.expand(sectionID);
page.section = sectionID;
}
if (articleID !== page.article) {
nav.find('a[href="#' + page.article + '"]').removeClass('active');
nav.find('a[href="#' + articleID + '"]').addClass('active');
page.article = articleID;
this.mobile(articleID);
}
}
在初始化过程中,他们会找出每个部分的高度
init: function(attribute) {
this.heights = this.page.nav.find('ul').map(function(idx, ele) {
return $(this).outerHeight();
}).get();
通过将这些功能附加到窗口的滚动,调整大小等事件,他们可以从这两个信息中突出显示用户正在查看的内容的正确输入。
答案 1 :(得分:1)
你可以通过html和css来做到这一点。它们为每个条目使用悬停样式,然后通过命名锚点链接到html内容。点击链接时,您可以在地址栏中看到。
E.g:
TOC录入:
<a href="#object.hasownproperty" class=""><code>hasOwnProperty</code></a>
内容正文:
<a name="object.hasownproperty"></a>
<!-- HTML Content here -->
当然,如果你想要漂亮的动画和东西,请使用
之类的东西http://www.position-absolute.com/articles/better-html-anchor-a-jquery-script-to-slide-the-scrollbar/或http://css-plus.com/2011/03/plusanchor-jquery-plugin/
<强>更新强>
实现突出显示(伪代码):
onscroll
事件处理程序附加到正文onscroll
,查看每个部分的scrollTop
top
您可以将TOC锚点命名为与部分id
匹配的方式。然后,只需说出#id
即可轻松检索相应的TOC条目,并将其添加到其中。