@2lkit/tocbot 中文文档教程

发布于 3年前 浏览 27 项目主页 更新于 3年前

Tocbot

github-actions

Tocbot 构建一个表格HTML 文档中标题的内容 (TOC)。 这对于文档网站或长降价页面很有用,因为它使它们更易于导航。 这个库的灵感来自 Tocify,主要区别在于 Tocbot 使用原生 DOM 方法并避免了 jQuery & jQuery UI 依赖项。

Get Started

您可以使用 npm 安装它或将脚本包含在带有 HTML 的页面上。

在这里下载

Include JS

用 npm 安装它。

npm install --save tocbot

或者

在页面底部的结束正文标记之前包含脚本。

<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.min.js"></script>

Include CSS

CSS 用于扩展 & 折叠分组和一些基本样式。

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.css">

或者

,如果您使用 npm 安装它并使用 sass / postcss,您可以尝试从“node_modules”导入样式,请参阅 includePath 选项文档了解更多信息

@import 'tocbot/src/scss/tocbot';

Usage

在页面底部结束正文标记之前初始化脚本。

tocbot.init({
  // Where to render the table of contents.
  tocSelector: '.js-toc',
  // Where to grab the headings to build the table of contents.
  contentSelector: '.js-toc-content',
  // Which headings to grab inside of the contentSelector element.
  headingSelector: 'h1, h2, h3',
  // For headings inside relative or absolute positioned containers within content.
  hasInnerContainers: true,
});

注意: 确保正文是可滚动的并且文档标题具有 id 属性,tocbot 和您的浏览器需要这些东西来使哈希跳转到正确的标题,一些降价库(如 marked) 已经为你做了这个。

如果 div 中的内容已更改,则触发刷新(可选地使用新选项)。

tocbot.refresh();

你也可以在 typescript 中使用它:

import * as tocbot from 'tocbot';

tocbot.init({
  // Options
});

tocbot.refresh();

tocbot.destroy();

Examples

如果你想将你的页面添加到这个列表中,请打开一个 pull request。

Requirements

该库使用 vanilla JavaScript。 它只有不到 350 字节的 CSS 和大约 3.6Kb 的 JavaScript(压缩和 gzip 压缩),它也没有依赖项。

此脚本适用于所有现代浏览器和 IE 9+

确保呈现的标题具有 id 属性,一些降价库(如 marked)已经这样做了。 如果您需要执行此客户端操作,请参阅此脚本

注意:要从平滑滚动中排除锚元素,请添加类 no-smooth-scroll

Fixed headers

要使用 tocbot 处理固定标头,只需将标头偏移量作为选项传递给 tocbot。 例如,40px 高固定标头所需的选项为:

tocbot.init({
  headingsOffset: 40,
  scrollSmoothOffset: -40
})

API

Options

// Where to render the table of contents.
tocSelector: '.js-toc',
// Or, you can pass in a DOM node instead
tocElement: element,
// Where to grab the headings to build the table of contents.
contentSelector: '.js-toc-content',
// Or, you can pass in a DOM node instead
contentElement: element,
// Which headings to grab inside of the contentSelector element.
headingSelector: 'h1, h2, h3',
// Headings that match the ignoreSelector will be skipped.
ignoreSelector: '.js-toc-ignore',
// For headings inside relative or absolute positioned containers within content
hasInnerContainers: false,
// Main class to add to links.
linkClass: 'toc-link',
// Extra classes to add to links.
extraLinkClasses: '',
// Class to add to active links,
// the link corresponding to the top most heading on the page.
activeLinkClass: 'is-active-link',
// Main class to add to lists.
listClass: 'toc-list',
// Extra classes to add to lists.
extraListClasses: '',
// Class that gets added when a list should be collapsed.
isCollapsedClass: 'is-collapsed',
// Class that gets added when a list should be able
// to be collapsed but isn't necessarily collapsed.
collapsibleClass: 'is-collapsible',
// Class to add to list items.
listItemClass: 'toc-list-item',
// Class to add to active list items.
activeListItemClass: 'is-active-li',
// How many heading levels should not be collapsed.
// For example, number 6 will show everything since
// there are only 6 heading levels and number 0 will collapse them all.
// The sections that are hidden will open
// and close as you scroll to headings within them.
collapseDepth: 0,
// Smooth scrolling enabled.
scrollSmooth: true,
// Smooth scroll duration.
scrollSmoothDuration: 420,
// Smooth scroll offset.
scrollSmoothOffset: 0,
// Callback for scroll end.
scrollEndCallback: function (e) {},
// Headings offset between the headings and the top of the document (this is meant for minor adjustments).
headingsOffset: 1,
// Timeout between events firing to make sure it's
// not too rapid (for performance reasons).
throttleTimeout: 50,
// Element to add the positionFixedClass to.
positionFixedSelector: null,
// Fixed position class to add to make sidebar fixed after scrolling
// down past the fixedSidebarOffset.
positionFixedClass: 'is-position-fixed',
// fixedSidebarOffset can be any number but by default is set
// to auto which sets the fixedSidebarOffset to the sidebar
// element's offsetTop from the top of the document on init.
fixedSidebarOffset: 'auto',
// includeHtml can be set to true to include the HTML markup from the
// heading node instead of just including the textContent.
includeHtml: false,
// includeTitleTags automatically sets the html title tag of the link
// to match the title. This can be useful for SEO purposes or
// when truncating titles.
includeTitleTags: false,
// onclick function to apply to all links in toc. will be called with
// the event as the first parameter, and this can be used to stop,
// propagation, prevent default or perform action
onClick: function (e) {},
// orderedList can be set to false to generate unordered lists (ul)
// instead of ordered lists (ol)
orderedList: true,
// If there is a fixed article scroll container, set to calculate titles' offset
scrollContainer: null,
// prevent ToC DOM rendering if it's already rendered by an external system
skipRendering: false,
// Optional callback to change heading labels.
// For example it can be used to cut down and put ellipses on multiline headings you deem too long.
// Called each time a heading is parsed. Expects a string and returns the modified label to display.
// Additionally, the attribute `data-heading-label` may be used on a heading to specify
// a shorter string to be used in the TOC.
// function (string) => string
headingLabelCallback: false,
// ignore headings that are hidden in DOM
ignoreHiddenElements: false,
// Optional callback to modify properties of parsed headings.
// The heading element is passed in node parameter and information parsed by default parser is provided in obj parameter.
// Function has to return the same or modified obj.
// The heading will be excluded from TOC if nothing is returned.
// function (object, HTMLElement) => object | void
headingObjectCallback: null,
// Set the base path, useful if you use a `base` tag in `head`.
basePath: '',
// Only takes affect when `tocSelector` is scrolling,
// keep the toc scroll position in sync with the content.
disableTocScrollSync: false

Methods

.init

使用选项对象初始化 tocbot。

tocbot.init(options)

.destroy

销毁 tocbot 并删除事件侦听器。

tocbot.destroy()

.refresh

如果文档更改并且需要重建,请刷新 tocbot。

tocbot.refresh()

Troubleshooting

  • Tocbot scrolls to the right position onClick but highlighting doesn't seem to show the active section
  • Try running this from the console: tocbot.refresh({ ...tocbot.options, hasInnerContainers: true }). If that works then one option (hasInnerContainers: true) to handle inner containers should be all you need to add.

Contributing

欢迎贡献和建议! 如果您遇到问题或有功能请求,请随时打开问题。 我会尽力及时回复。

如果你想打开一个 pull request,只需 fork 回购,但请确保所有测试和 lint 通过。

Running Tests

npm run test

Steps to publish

  • Push a branch and open a pull request
  • run npm version <patch|minor|major>
  • Update readme.md with notes
  • Merge the pull request
  • commit dist/
  • run npm publish
  • make release on github

License

麻省理工学院

Tocbot

github-actions

Tocbot builds a table of contents (TOC) from headings in an HTML document. This is useful for documentation websites or long markdown pages because it makes them easier to navigate. This library was inspired by Tocify, the main difference is that Tocbot uses native DOM methods and avoids the jQuery & jQuery UI dependencies.

Get Started

You can use npm to install it or include the script on the page with HTML.

Download it here

Include JS

Install it with npm.

npm install --save tocbot

OR

Include the script at the bottom of the page before the closing body tag.

<script src="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.min.js"></script>

Include CSS

CSS is used for expanding & collapsing groupings and some basic styling.

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/tocbot/4.11.1/tocbot.css">

OR

If you installed it with npm and use sass / postcss you might try importing the styles from 'node_modules', see the includePath option documentation for more info

@import 'tocbot/src/scss/tocbot';

Usage

Initialize the script at the bottom of the page before the closing body tag.

tocbot.init({
  // Where to render the table of contents.
  tocSelector: '.js-toc',
  // Where to grab the headings to build the table of contents.
  contentSelector: '.js-toc-content',
  // Which headings to grab inside of the contentSelector element.
  headingSelector: 'h1, h2, h3',
  // For headings inside relative or absolute positioned containers within content.
  hasInnerContainers: true,
});

NOTE: Make sure the body is scrollable and the document headings have id attributes, tocbot and your browser needs these things to make hashes jump to the proper heading, some markdown libraries (like marked) already do this for you.

If content in the div has changed then trigger a refresh (optionally with new options).

tocbot.refresh();

Also you can use it within typescript:

import * as tocbot from 'tocbot';

tocbot.init({
  // Options
});

tocbot.refresh();

tocbot.destroy();

Examples

If you'd like to add your page to this list open a pull request.

Requirements

This library uses vanilla JavaScript. It is less than 350 bytes of CSS and about 3.6Kb of JavaScript (minified and gzipped) it also has no dependencies.

This script works in all modern browsers and IE 9+.

Make sure rendered headings have id attributes, some markdown libraries (like marked) already do this. If you need to do this client side see this script.

NOTE: to exclude anchor elements from smooth scrolling, add the class no-smooth-scroll.

Fixed headers

To handle fixed headers with tocbot, just pass the header offsets as options to tocbot. For example, the options needed for a 40px tall fixed header would be:

tocbot.init({
  headingsOffset: 40,
  scrollSmoothOffset: -40
})

API

Options

// Where to render the table of contents.
tocSelector: '.js-toc',
// Or, you can pass in a DOM node instead
tocElement: element,
// Where to grab the headings to build the table of contents.
contentSelector: '.js-toc-content',
// Or, you can pass in a DOM node instead
contentElement: element,
// Which headings to grab inside of the contentSelector element.
headingSelector: 'h1, h2, h3',
// Headings that match the ignoreSelector will be skipped.
ignoreSelector: '.js-toc-ignore',
// For headings inside relative or absolute positioned containers within content
hasInnerContainers: false,
// Main class to add to links.
linkClass: 'toc-link',
// Extra classes to add to links.
extraLinkClasses: '',
// Class to add to active links,
// the link corresponding to the top most heading on the page.
activeLinkClass: 'is-active-link',
// Main class to add to lists.
listClass: 'toc-list',
// Extra classes to add to lists.
extraListClasses: '',
// Class that gets added when a list should be collapsed.
isCollapsedClass: 'is-collapsed',
// Class that gets added when a list should be able
// to be collapsed but isn't necessarily collapsed.
collapsibleClass: 'is-collapsible',
// Class to add to list items.
listItemClass: 'toc-list-item',
// Class to add to active list items.
activeListItemClass: 'is-active-li',
// How many heading levels should not be collapsed.
// For example, number 6 will show everything since
// there are only 6 heading levels and number 0 will collapse them all.
// The sections that are hidden will open
// and close as you scroll to headings within them.
collapseDepth: 0,
// Smooth scrolling enabled.
scrollSmooth: true,
// Smooth scroll duration.
scrollSmoothDuration: 420,
// Smooth scroll offset.
scrollSmoothOffset: 0,
// Callback for scroll end.
scrollEndCallback: function (e) {},
// Headings offset between the headings and the top of the document (this is meant for minor adjustments).
headingsOffset: 1,
// Timeout between events firing to make sure it's
// not too rapid (for performance reasons).
throttleTimeout: 50,
// Element to add the positionFixedClass to.
positionFixedSelector: null,
// Fixed position class to add to make sidebar fixed after scrolling
// down past the fixedSidebarOffset.
positionFixedClass: 'is-position-fixed',
// fixedSidebarOffset can be any number but by default is set
// to auto which sets the fixedSidebarOffset to the sidebar
// element's offsetTop from the top of the document on init.
fixedSidebarOffset: 'auto',
// includeHtml can be set to true to include the HTML markup from the
// heading node instead of just including the textContent.
includeHtml: false,
// includeTitleTags automatically sets the html title tag of the link
// to match the title. This can be useful for SEO purposes or
// when truncating titles.
includeTitleTags: false,
// onclick function to apply to all links in toc. will be called with
// the event as the first parameter, and this can be used to stop,
// propagation, prevent default or perform action
onClick: function (e) {},
// orderedList can be set to false to generate unordered lists (ul)
// instead of ordered lists (ol)
orderedList: true,
// If there is a fixed article scroll container, set to calculate titles' offset
scrollContainer: null,
// prevent ToC DOM rendering if it's already rendered by an external system
skipRendering: false,
// Optional callback to change heading labels.
// For example it can be used to cut down and put ellipses on multiline headings you deem too long.
// Called each time a heading is parsed. Expects a string and returns the modified label to display.
// Additionally, the attribute `data-heading-label` may be used on a heading to specify
// a shorter string to be used in the TOC.
// function (string) => string
headingLabelCallback: false,
// ignore headings that are hidden in DOM
ignoreHiddenElements: false,
// Optional callback to modify properties of parsed headings.
// The heading element is passed in node parameter and information parsed by default parser is provided in obj parameter.
// Function has to return the same or modified obj.
// The heading will be excluded from TOC if nothing is returned.
// function (object, HTMLElement) => object | void
headingObjectCallback: null,
// Set the base path, useful if you use a `base` tag in `head`.
basePath: '',
// Only takes affect when `tocSelector` is scrolling,
// keep the toc scroll position in sync with the content.
disableTocScrollSync: false

Methods

.init

Initialize tocbot with an options object.

tocbot.init(options)

.destroy

Destroy tocbot and remove event listeners.

tocbot.destroy()

.refresh

Refresh tocbot if the document changes and it needs to be rebuilt.

tocbot.refresh()

Troubleshooting

  • Tocbot scrolls to the right position onClick but highlighting doesn't seem to show the active section
  • Try running this from the console: tocbot.refresh({ ...tocbot.options, hasInnerContainers: true }). If that works then one option (hasInnerContainers: true) to handle inner containers should be all you need to add.

Contributing

Contributions and suggestions are welcome! Please feel free to open an issue if you run into a problem or have a feature request. I'll do my best to respond in a timely fashion.

If you want to open a pull request just fork the repo but please make sure all tests and lint pass.

Running Tests

npm run test

Steps to publish

  • Push a branch and open a pull request
  • run npm version <patch|minor|major>
  • Update readme.md with notes
  • Merge the pull request
  • commit dist/
  • run npm publish
  • make release on github

License

MIT

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文