wordpress添加代码高亮显示

  • 2019-02-26 15:22:05
  • 3,534 次阅读
  • 稿源:天马行空

在用wordpress写博客时,平常需要在内容区域添加一些代码程序,但wordpress后台编辑文档中没有能够突出代码高亮显示的功能,这使得内容区域的文本内容与程序代码颜色一致,不能够重点突出代码程序,更不能达到用户体验的要求。

最近,看到一个国外的网站https://prismjs.com/,Prism是一个轻量级的、可扩展的语法亮点,它基于现代Web标准构建。它被用于数千个网站,包括一些你每天访问的网站。

通过点击最上面的download按钮,进入下载选择页面。它包括四个部分压缩水平(compression level),核心(core),语言(languages),插件(plugins),经过四部分的操作,可以定制自己喜欢的高亮显示代码,最后的一个环节将调好的模板的js代码和css样式下载放到自己的网站中。
高亮代码显示的样式,如下图:

codeHighlight
通过上面的图片可以看到显示的效果很漂亮,但是这种方法下面有个滚动条,隐藏的代码部分需要拖动出来。
下面介绍另一种,是我比较喜欢的一个方法,也是通css和js来实现的。

首先,在自己的模板中添加css样式,如下:

  1. /*淡白灰代码高亮样式*/
  2. pre {
  3. display: block;
  4. padding: 0 0 0 10px;
  5. margin: 0 0 10px;
  6. font-size: 14px;
  7. line-height: 20px;
  8. word-break: break-all;
  9. word-wrap: break-word;
  10. white-space: pre;
  11. white-space: pre-wrap;
  12. border: 1px solid rgba(0,0,0,.15);
  13. border-radius: 2px
  14. }
  15. pre.prettyprint {
  16. margin-bottom: 20px;
  17. background-image: linear-gradient(transparent 50%, rgba(69, 142, 209, 0.04) 50%);
  18. background-size: 3em 3em;
  19. }
  20. .prettyprint.linenums, pre.prettyprint.linenums {
  21. -webkit-box-shadow: inset 40px 0 0 #f8f8f8, inset 42px 0 0 #358ccb;;
  22. -moz-box-shadow: inset 40px 0 0 #f8f8f8, inset 42px 0 0 #358ccb;;
  23. box-shadow: inset 40px 0 0 #f8f8f8, inset 42px 0 0 #358ccb;
  24. }
  25. .prettyprint.linenums ol, pre.prettyprint.linenums ol {
  26. padding-left: 1.8em;
  27. font-family: Consolas, Monaco, 'Andale Mono', 'Ubuntu Mono', monospace;
  28. }
  29. .prettyprint.linenums ol li, pre.prettyprint.linenums ol li {
  30. padding-left: 6px;
  31. color: #bebec5;
  32. line-height: 21px;
  33. margin-left:3px;
  34. list-style: decimal;
  35. }
  36. .prettyprint.linenums ol li:before, pre.prettyprint.linenums ol li:before {
  37. content: "";
  38. width: 0
  39. }
  40. .prettyprint .com {
  41. color: #666
  42. }
  43. .prettyprint .lit {
  44. color: #c0c
  45. }
  46. .prettyprint .clo, .prettyprint .opn, .prettyprint .pun {
  47. color: #0a0
  48. }
  49. .prettyprint .fun {
  50. color: #dc322f
  51. }
  52. .prettyprint .atv, .prettyprint .str {
  53. color: #c28f5b
  54. }
  55. .prettyprint .kwd, .prettyprint .tag {
  56. color: #f92659
  57. }
  58. .prettyprint .atn, .prettyprint .dec, .prettyprint .typ, .prettyprint .var {
  59. color: #0a0
  60. }
  61. .prettyprint .pln {
  62. color: #00f
  63. }

其次,在header引用prettify.js代码

最后,在编辑器中添加高亮代码按钮,在function中加入

  1. function prettify_codeHighlight() {
  2. ?>
  3. <script type="text/javascript">
  4. QTags.addButton( 'codeHighlight', '代码高亮', '<pres class="prettyprint linenums" >\n添加代码\n</pres>', "" );//添加高亮代码
  5. </script>
  6. <?php
  7. }
  8. add_action('admin_print_footer_scripts', 'prettify_codeHighlight' );

注:将上面的pres改成pre,因为pres是不存在的标签,问了避免与代码中的pre class=”prettyprint linenums冲突,我这里发布内容时故意写成这样的。

喜欢 2

文章评论 (0)

表情

大眼 可爱 大笑 坏笑 害羞 发怒 折磨 快哭了 大哭 白眼 晕 流汗 困 腼腆 惊讶 憨笑 色 得意 骷髅 囧 睡觉 眨眼 亲亲 疑问 闭嘴 难过 淡定 抗议 鄙视 猪头