后台:编辑器中添加高亮样式
第一步:编辑器页面加载js和css文件。
<script src="kindeditor-4.1.4/kindeditor.js" type="text/javascript" charset="utf-8"></script> <script src="kindeditor-4.1.4/plugins/code/prettify.js" type="text/javascript"></script> <link href="kindeditor-4.1.4/plugins/code/prettify.css" rel="stylesheet" type="text/css" />
上面注意修改文件路径。
第二步:编辑器初始化设置后,在里面加cssPath(注意路径)和prettyPrint(),这样在编辑器中插入的代码才有样式:
KindEditor.ready(function (K) { window.EditorObject = K.create('#txtBody', { cssPath: 'plugins/code/prettify.css', resizeType: 1, allowPreviewEmoticons: false, allowImageUpload: false, items: [ 'code', 'fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline', 'removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist', 'insertunorderedlist', '|', 'emoticons', 'image', 'link'] }); prettyPrint(); });
假如要高亮的代码一开始是隐藏的,要显示出来,则需要调用prettyPrint();
function Show(i) { var id = '#divBody' + i; if($(id).is(":hidden")){ $('#divIntro' + i).hide(); $(id).slideDown(); $(id).next("a").text("收缩..."); prettyPrint(); } else{ $('#divIntro' + i).show(); $(id).slideUp(); $(id).next("a").text("详细..."); } }
pre.prettyprint { border: 0; border-left: 3px solid rgb(204, 204, 204); margin-left: 2em; padding: 0.5em; font-size: 110%; display: block; font-family: "Consolas", "Monaco", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace; margin: 1em 0px; white-space: pre-wrap; /* 原来的值是 pre;*/ }上面样式是只有一条左边框,不太好看,修改为类似博客园的代码插入风格:四周边框、有背景颜色
pre.prettyprint { border: 1px solid rgb(204, 204, 204); background-color:#F8F8F8; margin-left: 2em; padding: 0.5em; font-size: 110%; display: block; font-family: "Consolas", "Monaco", "Bitstream Vera Sans Mono", "Courier New", Courier, monospace; margin: 1em 0px; white-space: pre-wrap; }到此为止 后端的编辑器中就能正常的显示高亮代码模块儿了。而且是实时的哦。到这里还没完呢继续往下看。后端虽然可以显示了但是前段还不可以哦。
前端:
第一步:加载需要的css和js 并执行prettyPrint();方法
<script src="kindeditor-4.1.4/plugins/code/prettify.js" type="text/javascript"></script> <link href="kindeditor-4.1.4/plugins/code/prettify.css" rel="stylesheet" type="text/css" /> <script>prettyPrint();</script>
到此为止就已经全部设置完成。可以愉快的体验你的代码高亮了。但是我还要告诉你一个bug,就是这篇文章不能再编辑,如果再次编辑的话代码高亮就不生效了,这个好像是和html解析有关系。解决方案没去研究,最近比较忙等有时间了去研究研究。
解决方案也找到了,就是在编辑的时候后端动态程序不能直接打印内容要对html进行转译一下就OK了目前完美。
除特别注明外,本站所有文章均为博文家原创,转载请注明出处来自https://www.32e.top/develop/lua/article-13.html
暂无评论