anchorate 是一个 JavaScript 库,可以帮助你创建锚点,滚动到锚点处,并创建目录。它可以让你的网页更加便于阅读和导航。在本文中,我们将学习如何使用 anchorate。
安装
首先,你需要安装 anchorate。你可以使用 npm 安装:
npm install anchorate --save
然后在你的 JavaScript 文件中导入 anchorate:
import anchorate from 'anchorate';
使用
在你的 HTML 文件中,为锚点添加 ID。例如:
<h2 id="section1">Section 1</h2> <p>Content of section 1</p> <h2 id="section2">Section 2</h2> <p>Content of section 2</p> <h2 id="section3">Section 3</h2> <p>Content of section 3</p>
在你的 JavaScript 文件中,调用 anchorate:
// www.javascriptcn.com code example
// 指定锚点根元素
const anchorsRoot = document.body;
// 指定标题元素
const header = 'h2';
// 指定目录的根元素
const tocRoot = document.getElementById('toc');
// 调用 anchorate
anchorate({
root: anchorsRoot,
headers: header,
toc: tocRoot
});参数
anchorate 接受下列参数:
root:指定锚点根元素,必须是一个 DOM 元素,默认为document.body。headers:指定标题元素,可以是一个字符串例如'h2',也可以是一个选择器例如'h2, h3'。默认为'h2, h3, h4, h5, h6'。toc:指定目录的根元素,必须是一个 DOM 元素或选择器。默认为null,不创建目录。index:用作目录索引的 DOM 元素。默认为一个ul元素。indexClass:目录根元素的类名。默认为'anchorate-index'。itemClass:目录项的类名。默认为'anchorate-item'。activeClass:当前查看的目录项的类名。默认为'anchorate-active'。top:滚动到锚点的顶部边缘与窗口顶部之间的距离。默认为20。behavior:滚动的行为。默认为'smooth'。可以设置为'auto'。
示例
以下是完整的示例代码:
// www.javascriptcn.com code example
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>anchorate 示例</title>
</head>
<body>
<div id="toc"></div>
<h1>My Cool Article</h1>
<h2 id="section1">Section 1</h2>
<p>Content of section 1</p>
<h2 id="section2">Section 2</h2>
<p>Content of section 2</p>
<h2 id="section3">Section 3</h2>
<p>Content of section 3</p>
<script type="module">
import anchorate from 'anchorate';
const anchorsRoot = document.body;
const headers = 'h2';
const tocRoot = document.getElementById('toc');
anchorate({
root: anchorsRoot,
headers: headers,
toc: tocRoot
});
</script>
</body>
</html>结论
使用 anchorate 可以方便地创建锚点、滚动到锚点处和创建目录。我们在本文中详细介绍了如何安装和使用 anchorate,还讲解了该库的各种参数和示例代码。希望这篇文章能够帮助您更好地使用 anchorate。
Source: FunTeaLearn,Please indicate the source for reprints https://funteas.com/post/5eedb69ab5cbfe1ea061158d