最近在做组内的组件库,用到代码的高亮显示~
我查到的资料有syntaxhighlighter、highlight.js、prism.js
highlight.js官网 https://highlightjs.org/
syntaxhighlighter官网 http://alexgorbatchev.com/SyntaxHighlighter/
prism.js官网 http://prismjs.com/ 参考资料:http://c7sky.com/syntax-highlighting-with-prismjs.html#0-qzone-1-94908-d020d2d2a4e8d1a374a433f596ad1440
基本实现原理都是引入需要的JS文件和CSS样式,将要显示的代码封装在<pre><code></code></pre>标签中
syntaxhighlighter效果如图(shCoreDefault样式)
<link rel="stylesheet" type="text/css" href="../node_modules/syntaxhighlighter_3.0.83/styles/shCoreDefault.css"/> <pre class=" js;"> var myCustomFn = function ShowFn() { Ext.Msg.alert('消息框', "你调用了客户端的JavaScript函数"); } </pre> <script src="../node_modules/syntaxhighlighter_3.0.83/scripts/shCore.js"></script> <script src="../node_modules/syntaxhighlighter_3.0.83/scripts/shBrushJScript.js"></script> <script src="../node_modules/syntaxhighlighter_3.0.83/scripts/shBrushXml.js"></script> <script>SyntaxHighlighter.all();</script>
highlight.js效果如图(default样式)
<link rel="stylesheet" href="../node_modules/highlight/lib/vendor/highlight.js/styles/default.css"/> <script src="../node_modules/highlight/lib/vendor/highlight.js/highlight.pack.js"></script> <script>hljs.initHighlightingOnLoad();</script> <pre> <code class="css"> @font-face { font-family: Chunkfive; src: url('Chunkfive.otf'); } body, .usertext { color: #F0F0F0; background: #600; font-family: Chunkfive, sans; } @import url(print.css); @media print { a[href^=http]::after { content: attr(href) } } </code> </pre>
prism.js效果图
<link rel="stylesheet" href="../css/prism.css"/> <pre class="language-html">
<code> <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <p>kjfeiwjoiefj</p> </body> </html> </code>
</pre> <script src="../js/prism.js"></script>
我们的项目前端用的是Anjularjs,据说用Angularjs和第三方js库结合的时候会有坑~有待研究。。。
后来我们采用的是Angular-highlightjs,主要是和Angularjs更好的兼容吧~
github上的地址:https://github.com/pc035860/angular-highlightjs
<link rel="stylesheet" href="../node_modules/highlight.js/styles/github.css"/> <script src="../node_modules/highlight.js/highlight.min.js"></script> <body ng-app="myApp"> <div hljs> @font-face { font-family: Chunkfive; src: url('Chunkfive.otf'); } body, .usertext { color: #F0F0F0; background: #600; font-family: Chunkfive, sans; } @import url(print.css); @media print { a[href^=http]::after { content: attr(href) } } </div>
<script src="../node_modules/angular/angular.min.js"></script> <script src="../node_modules/angular-highlightjs/angular-highlightjs.min.js"></script> <script> var myApp = angular.module('myApp', ['hljs']); </script>