本文介紹下我在實現文章錨點過程中的思路、遇到的問題和解決方法
最終實現效果如下:
單純用前端來實現是很簡單的,我用的是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作為錨點內容
根據數據進行頁面渲染: