Markdown使用 - 如何定义锚(链接)、引用锚(网址链接)

本文介绍了Markdown中如何定义和使用页内锚点,包括标准Markdown语法、CDN与简书的特殊处理,以及锚点的正确放置以优化用户体验。提供多个样例,帮助读者理解和应用。
摘要由CSDN通过智能技术生成

更多Markdown使用技巧,可参考《Markdown使用方法、常用技巧汇总》

Markdown中,锚的使用对阅读体验有很大的提升,但不同工具、平台对锚的支持不尽相同,踩了不少坑,整理做个记录和分享。

使用锚点的方式普遍相同:

  • 页外链接:[描述](url)
    页外链接比较简单,拿到url按上面写法即可使用。如点我去首页
  • 页内锚点:[描述](#id)
    页内锚点的引用方式如上,但定义的方式有些不同。这是在markdown编写时常遇到的问题。下面主要介绍该项。

如何定义页内锚点

尽管Markdown是HTML的子集,但不同Markdown工具对语法的解释和支持有一些出入:

  • 标准markdown语法支持<a name=xxx></a>
  • csdn、简书等不支持,需要使用<a id=xxx></a><h5 id=xxx>xxx</h5>的方式;

    注意该链接会直接跳到页面顶部,如果考虑体验,可以将锚放置在目标元素上面一行。

在 Vue 中使用 Markdown 生成文档时,可以通过以下步骤自动生成侧边栏目录: 1. 在项目中安装 `markdown-it` 和 `markdown-it-anchor` 库: ```bash npm install markdown-it markdown-it-anchor --save ``` 2. 在 Vue 组件中引入并初始化 `markdown-it` 和 `markdown-it-anchor`: ```javascript import MarkdownIt from 'markdown-it' import MarkdownItAnchor from 'markdown-it-anchor' const md = new MarkdownIt({ html: true, linkify: true, typographer: true, }) md.use(MarkdownItAnchor) ``` 3. 在 Vue 组件中使用 `v-html` 指令渲染 Markdown 文本,并使用 `@hook:mounted` 钩子函数监听渲染完成事件,在事件处理函数中获取文档中所有标题标签(如 `h1`、`h2` 等),并根据标题级别生成目录树: ```html <template> <div> <div v-html="html"></div> <div class="sidebar"> <ul> <li v-for="item in toc" :key="item.id"> <a :href="'#' + item.id">{{ item.text }}</a> <ul v-if="item.children"> <li v-for="child in item.children" :key="child.id"> <a :href="'#' + child.id">{{ child.text }}</a> </li> </ul> </li> </ul> </div> </div> </template> <script> export default { data() { return { html: '', toc: [], } }, mounted() { this.html = md.render('# Hello World\n## Introduction\n### Features\n### Installation\n## Usage\n## API Reference') this.$nextTick(() => { const headers = Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6')) this.toc = headers.map(header => ({ id: header.id, text: header.textContent, level: Number(header.tagName[1]), })).reduce((acc, header) => { let lastItem = acc[acc.length - 1] if (!lastItem || header.level <= lastItem.level) { acc.push(header) } else { let parent = lastItem while (parent.children && header.level > parent.level) { parent = parent.children[parent.children.length - 1] } if (!parent.children) { parent.children = [] } parent.children.push(header) } return acc }, []) }) }, } </script> ``` 4. 在 Vue 组件的样式中定义侧边栏样式: ```css .sidebar { position: fixed; top: 0; right: 0; bottom: 0; width: 200px; padding: 20px; overflow-y: auto; } ``` 这样就可以在 Vue Markdown 文档中自动生成侧边栏目录了。当然,这只是一个简单的示例,实际项目中可能需要根据具体需求进行一些定制化调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值