首页 > 其他 > 详细

实现在文章下 锚点跳转到标题的功能

时间:2020-05-26 13:45:58      阅读:56      评论:0      收藏:0      [点我收藏+]

  本文介绍下我在实现文章锚点过程中的思路、遇到的问题和解决方法

最终实现效果如下:

技术分享图片

 

单纯用前端来实现是很简单的,我用的是AntDesignVue的Anchor组件,拷贝Demo代码就能看到Anchor的实现效果。

贴个Demo的代码

<template>
  <a-anchor>
    <a-anchor-link href="#components-anchor-demo-basic" title="Basic demo" />
    <a-anchor-link href="#components-anchor-demo-static" title="Static demo" />
    <a-anchor-link
      href="#components-anchor-demo-basic"
      title="Basic demo with Target"
      target="_blank"
    />
    <a-anchor-link href="#API" title="API">
      <a-anchor-link href="#Anchor-Props" title="Anchor Props" />
      <a-anchor-link href="#Link-Props" title="Link Props" />
    </a-anchor-link>
  </a-anchor>
</template>

从代码中可以轻易发现,锚点是由多个<a-anchor-link>组成的,titile指显示的值,href指需要跳转到的页面元素的id值。

也就是说要实现点击锚点跳转到指定的标题,需要给<a-anchor-link>指定 href、并且页面元素中得有这个id。

 

讲完了上面这些,下面来看下我在项目中是如何实现 解析和处理文章内容、动态生成锚点的

思路:

技术分享图片

 

 

 按照这个流程下来是能实现锚点跳转的。我之前是卡在了后台文章上传时没有对<h1>标签动态追加id,导致锚点无法匹配到页面中对应Id的<h1>标签。

贴一个js操作dom给h1追加id的代码

技术分享图片

 

 

 技术分享图片

 

 

 

 

 前台文章展示

正则解析h1作为锚点内容

技术分享图片

 

 根据数据进行页面渲染:

技术分享图片

 

实现在文章下 锚点跳转到标题的功能

原文:https://www.cnblogs.com/clsl/p/12960905.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!