像JavaScript-Garden这样的内容列表

时间:2011-07-25 15:27:58

标签: javascript jquery

我想创建一个类似于JavaScript Gardens的内容表。他们如何确定哪个部分当前处于活动状态?您是否有任何推荐的JavaScript库可以解决此问题?

编辑:所以我要求的是如何在用户滚动时知道屏幕上哪个部分当前处于活动状态,以便我可以在内容列表中突出显示该部分。

2 个答案:

答案 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/

<强>更新

实现突出显示(伪代码):

  1. 保留所有部分的标签
  2. onscroll事件处理程序附加到正文
  3. onscroll,查看每个部分的scrollTop top
  4. 如果找到匹配项,请从之前的TOC条目中删除突出显示类,并将其添加到新的TOC条目。
  5. 您可以将TOC锚点命名为与部分id匹配的方式。然后,只需说出#id即可轻松检索相应的TOC条目,并将其添加到其中。