網頁程式碼塊語法高亮
阿新 • • 發佈:2020-07-27
目錄
程式碼塊高亮
作為一個偶爾會寫寫部落格的程式設計師,對於程式碼高亮還是很感興趣的,終於在今天探索了一下,滿足了一大心願~
預備知識
- 瞭解了 highlight.js(程式碼高亮外掛)
- 官方教程(挺簡短的幾步就行)
- 使用 highlightjs 點亮你的程式碼(網友教程,寫的挺好)
- 不高亮給
code
標籤使用class="plaintext" 或者 class="nohighlight"
- highlightjs-line-numbers.js(文件英語不難)
- 坑:注意自定義樣式的優先順序(莫名多出了幾個樣式)
- 單行需要指定才會顯示行號
- 可以規定起始行號
- 不顯示行號給
code
標籤使用class="nohljsln"
- 坑:注意自定義樣式的優先順序(莫名多出了幾個樣式)
必要歩鄹:資料處理(html轉義)
- 線上工具,操作簡單
部落格:【JS】JS實現Html轉義和反轉義(html編碼和解碼)的方法總結
// 上面部落格擷取的程式碼(html 轉義) function htmlEncode (html){ //1.首先動態建立一個容器標籤元素,如DIV var temp = document.createElement ("div"); //2.然後將要轉換的字串設定為這個元素的innerText或者textContent (temp.textContent != undefined ) ? (temp.textContent = html) : (temp.innerText = html); //3.最後返回這個元素的innerHTML,即得到經過HTML編碼轉換的字串了 var output = temp.innerHTML; temp = null; return output; }
demo 效果(期望效果)
個人demo程式碼
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> <!-- 程式碼整體風格檔案,去styles 檔案裡選一下 --> <link rel="stylesheet" href="./styles/a11y-dark.css"> <!-- hightlight 官網打包好的js檔案 --> <script src="./highlight.pack.js"></script> <!-- --> <script src="https://cdn.bootcdn.net/ajax/libs/highlightjs-line-numbers.js/2.8.0/highlightjs-line-numbers.min.js"></script> <script> hljs.initHighlightingOnLoad(); hljs.initLineNumbersOnLoad({ // 讓單行的時候也顯示行號 singleLine: true }); </script> <style type="text/css"> body{ background-color: rgb(240,240,240); } #contianer{ width: 75vw; margin: 0 auto; } /* for block of numbers */ pre code .hljs-ln-numbers { -webkit-touch-callout: none; -webkit-user-select: none; -khtml-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; text-align: right; color: #ccc; border-right: 1px solid #CCC; vertical-align: top; padding-right: 5px; /* your custom style here */ } /* for block of code */ pre code .hljs-ln-code { padding-left: 10px; /* padding-left: 30px; */ } </style> </head> <body> <div id="contianer"> <h1>這是其他的文字</h1> <pre class="vue"> <code data-ln-single-line="true"> <template> <router-view/> </template> <script> export default { name: 'App' }; </script> ![](https://img2020.cnblogs.com/blog/1725797/202007/1725797-20200727210425586-887146204.png) <style lang="less"> </style> </code> </pre> <h2>程式碼塊2</h2> <pre class="python"> <code data-ln-single-line="true">print("hello world!")</code> </pre> <h2>行號從10開始的程式碼塊</h2> <pre class="vue"> <code data-ln-start-from="10"> <template> <router-view/> </template> <script> export default { name: 'App' }; </script> <style lang="less"> </style> </code> </pre> <h2>不顯示行號</h2> <pre class="vue"> <!-- 通過 class="nohljsln" 來取消行號 --> <code class="nohljsln" data-ln-start-from="10"> <template> <router-view/> </template> <script> export default { name: 'App' }; </script> <style lang="less"> </style> </code> </pre> </div> </body> </html>
結合業務
比如網站上要展示使用者程式碼了,可以獲取到程式碼,通過html轉義(前面那段js程式碼方法呼叫一下),渲染到 code 標籤裡
(試了個測試demo,崩了,後續想起來再補吧)
ps:實際用途不太大的
程式碼壓縮包(demo 程式碼)
崩了就不放了