ckeditor实时监听编辑内容变化
html文件部分:
<textarea id="editor" type="text" name="comment" class="ckeditor" ></textarea>
<script src="/static/ckeditor/ckeditor.js">
CKEDITOR.replace('editor',{height : 800,enterMode:2,forceEnterMode:false,shiftEnterMode:1,tabSpaces:12,allowedContent: true});
//这一步是使textarea编辑器使用ckeditor。
CKEDITOR.instances['editor'].on('change', function(e) {
if (e.editor.checkDirty()) {
yl();
} });
//这一步是监听编辑内容的变化,当有变化时调用yl()方法。
</script>
代码解读:
一:ckeditor基本使用:
ckeditor4一般和textarea编辑器一起使用,然后在script中用CKEDITOR.replace方法参数添加textarea的id,即可实现ckeditor嵌套textarea,同时这也是使用ckeditor必要的方法。
二:ckeditor添加监听:
CKEDITOR.instances方法可以添加监听,可以监听ckeditor的各种事件,其中’change’为监听ckeditor变化,包含编辑内容的变化。
完整代码如下:
<html lang="zh-CN">
<head>
<script src="/static/ckeditor/ckeditor.js"></script>
</head>
<script>
function yl(){
var stt=CKEDITOR.instances.editor.getData();//获取ckeditor内容,id=editor
stt = stt.replace('<br />', '');//执行操作,这里是替换
var ylbq=document.getElementById('ylnr');//获取需要展示编辑器内容的标签id
ylbq.innerHTML=stt;
}
</script>
<body>
<textarea id="editor" type="text" name="comment" class="ckeditor" ></textarea>
<script>
CKEDITOR.replace('comment',{height : 200,enterMode:2,forceEnterMode:false,shiftEnterMode:1,tabSpaces:12,allowedContent: true});
//这一步是使textarea编辑器使用ckeditor。
CKEDITOR.instances['editor'].on('change', function(e) {
if (e.editor.checkDirty()) {
yl();
} });
//这一步是监听编辑内容的变化,当有变化时调用yl()方法。
</script>
<div style="float: left;text-align:left;width:990px;height: 400px;padding-left:10px;background-color: white;border:1px solid #ccc;">
<span><a id="ylnr" style="white-space: pre-wrap;word-wrap: break-word; width:990px;font-size:14px;"></a></span>
</div>
</body>
</html>
效果如图:
总结:
亲测可用,关于script src=“/static/ckeditor/ckeditor.js”,中是否指定src,不同的情况是不一样的,各位可以自己测试。但是事先得下载ckeditor包。关于ckeditor的使用,网上有很多教程,但是django要在前端使用ckeditor实际步骤不需要那么繁琐,网上的教程大多是介绍django管理页面如何使用ckeditor的。而django前端使用仅仅只需要两步:
1:下载ckeditor包,导入django目录
2:直接在html页面script中使用
各位如果只要前端页面使用ckeditor编辑器,那么可以按这两步操作就行。最后希望大家多关注技术交流网(www.js1331.com),本文转载https://www.js1331.com/jiaocheng?id=280135。