kindEditor 使用
1. kindEditor简介:
KindEditor是一套开源的HTML可视化编辑器,主要用于让用户在网站上获得所见即所得编辑效果。
主要特点:
1. 体积小,加载速度快,但功能十分丰富。2. 内置自定义range,完美地支持span标记。
3. 基于插件的方式设计,所有功能都是插件,增加自定义和扩展功能非常简单。
4. 修改编辑器风格很容易,只需修改一个CSS文件。
5. 支持大部分主流浏览器,比如IE、Firefox、Safari、Chrome、Opera。
界面效果:

官网地址:http://kindeditor.net/demo.php
下载:http://kindeditor.net/down.php
文件目录说明:
├── asp asp示例
├── asp.net asp.net示例
├── attached 空文件夹,放置关联文件attached
├── examples HTML示例
├── jsp java示例
├── kindeditor-all-min.js 全部JS(压缩)
├── kindeditor-all.js 全部JS(未压缩)
├── kindeditor-min.js 仅KindEditor JS(压缩)
├── kindeditor.js 仅KindEditor JS(未压缩)
├── lang 支持语言
├── license.txt License
├── php PHP示例
├── plugins KindEditor内部使用的插件
└── themes KindEditor主题
2. 基本使用
<textarea name="content" id="content"></textarea>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
<script>
$(function () {
initKindEditor();
});
function initKindEditor() {
var kind = KindEditor.create('#content', {
width: '100%', // 文本框宽度(可以百分比或像素)
height: '300px', // 文本框高度(只能像素)
minWidth: 200, // 最小宽度(数字)
minHeight: 400 // 最小高度(数字)
});
}
</script>
3. 相关参数:
4. 重点实例(上传文件)
前端html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div>
<h1>文章内容</h1>
{{ request.POST.content|safe }}
</div>
<form method="POST">
<h1>请输入内容:</h1>
{% csrf_token %}
<div style="width: 500px; margin: 0 auto;">
<textarea name="content" id="content"></textarea>
</div>
<input type="submit" value="提交"/>
</form>
<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/plugins/kind-editor/kindeditor-all.js"></script>
<script>
$(function () {
initKindEditor();
});
function initKindEditor() {
var a = 'kind';
var kind = KindEditor.create('#content', {
width: '100%', // 文本框宽度(可以百分比或像素)
height: '300px', // 文本框高度(只能像素)
minWidth: 200, // 最小宽度(数字)
minHeight: 400, // 最小高度(数字)
uploadJson: '/kind/upload_img/',
extraFileUploadParams: {
'csrfmiddlewaretoken': '{{ csrf_token }}'
},
fileManagerJson: '/kind/file_manager/',
allowPreviewEmoticons: true,
allowImageUpload: true
});
}
</script>
</body>
</html>
后端视图函数views.py
import os
import json
import time
from django.shortcuts import render
from django.shortcuts import HttpResponse
def index(request):
"""
首页
:param request:
:return:
"""
return render(request, 'index.html')
def upload_img(request):
"""
文件上传
:param request:
:return:
"""
dic = {
'error': 0,
'url': '/static/imgs/20130809170025.png',
'message': '错误了...'
}
return HttpResponse(json.dumps(dic))
def file_manager(request):
"""
文件管理
:param request:
:return:
"""
dic = {}
root_path = '/Users/wupeiqi/PycharmProjects/editors/static/'
static_root_path = '/static/'
request_path = request.GET.get('path')
if request_path:
abs_current_dir_path = os.path.join(root_path, request_path)
move_up_dir_path = os.path.dirname(request_path.rstrip('/'))
dic['moveup_dir_path'] = move_up_dir_path + '/' if move_up_dir_path else move_up_dir_path
else:
abs_current_dir_path = root_path
dic['moveup_dir_path'] = ''
dic['current_dir_path'] = request_path
dic['current_url'] = os.path.join(static_root_path, request_path)
file_list = []
for item in os.listdir(abs_current_dir_path):
abs_item_path = os.path.join(abs_current_dir_path, item)
a, exts = os.path.splitext(item)
is_dir = os.path.isdir(abs_item_path)
if is_dir:
temp = {
'is_dir': True,
'has_file': True,
'filesize': 0,
'dir_path': '',
'is_photo': False,
'filetype': '',
'filename': item,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}
else:
temp = {
'is_dir': False,
'has_file': False,
'filesize': os.stat(abs_item_path).st_size,
'dir_path': '',
'is_photo': True if exts.lower() in ['.jpg', '.png', '.jpeg'] else False,
'filetype': exts.lower().strip('.'),
'filename': item,
'datetime': time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime(os.path.getctime(abs_item_path)))
}
file_list.append(temp)
dic['file_list'] = file_list
return HttpResponse(json.dumps(dic))
5. XSS过滤特殊标签
处理依赖:
pip3 install beautifulsoup4
XSS示例:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
class XSSFilter(object):
__instance = None
def __init__(self):
# XSS白名单
self.valid_tags = {
"font": ['color', 'size', 'face', 'style'],
'b': [],
'div': [],
"span": [],
"table": [
'border', 'cellspacing', 'cellpadding'
],
'th': [
'colspan', 'rowspan'
],
'td': [
'colspan', 'rowspan'
],
"a": ['href', 'target', 'name'],
"img": ['src', 'alt', 'title'],
'p': [
'align'
],
"pre": ['class'],
"hr": ['class'],
'strong': []
}
@classmethod
def instance(cls):
if not cls.__instance:
obj = cls()
cls.__instance = obj
return cls.__instance
def process(self, content):
soup = BeautifulSoup(content, 'lxml')
# 遍历所有HTML标签
for tag in soup.find_all(recursive=True):
# 判断标签名是否在白名单中
if tag.name not in self.valid_tags:
tag.hidden = True
if tag.name not in ['html', 'body']:
tag.hidden = True
tag.clear()
continue
# 当前标签的所有属性白名单
attr_rules = self.valid_tags[tag.name]
keys = list(tag.attrs.keys())
for key in keys:
if key not in attr_rules:
del tag[key]
return soup.renderContents()
if __name__ == '__main__':
html = """<p class="title">
<b>The Dormouse's story</b>
</p>
<p class="story">
<div name='root'>
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
and they lived at the bottom of a well.
<script>alert(123)</script>
</div>
</p>
<p class="story">...</p>"""
v = XSSFilter.instance().process(html)
print(v)
基于__new__实现单例模式示例:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
from bs4 import BeautifulSoup
class XSSFilter(object):
__instance = None
def __init__(self):
# XSS白名单
self.valid_tags = {
"font": ['color', 'size', 'face', 'style'],
'b': [],
'div': [],
"span": [],
"table": [
'border', 'cellspacing', 'cellpadding'
],
'th': [
'colspan', 'rowspan'
],
'td': [
'colspan', 'rowspan'
],
"a": ['href', 'target', 'name'],
"img": ['src', 'alt', 'title'],
'p': [
'align'
],
"pre": ['class'],
"hr": ['class'],
'strong': []
}
def __new__(cls, *args, **kwargs):
"""
单例模式
:param cls:
:param args:
:param kwargs:
:return:
"""
if not cls.__instance:
obj = object.__new__(cls, *args, **kwargs)
cls.__instance = obj
return cls.__instance
def process(self, content):
soup = BeautifulSoup(content, 'lxml')
# 遍历所有HTML标签
for tag in soup.find_all(recursive=True):
# 判断标签名是否在白名单中
if tag.name not in self.valid_tags:
tag.hidden = True
if tag.name not in ['html', 'body']:
tag.hidden = True
tag.clear()
continue
# 当前标签的所有属性白名单
attr_rules = self.valid_tags[tag.name]
keys = list(tag.attrs.keys())
for key in keys:
if key not in attr_rules:
del tag[key]
return soup.renderContents()
if __name__ == '__main__':
html = """<p class="title">
<b>The Dormouse's story</b>
</p>
<p class="story">
<div name='root'>
Once upon a time there were three little sisters; and their names were
<a href="http://example.com/elsie" class="sister c1" style='color:red;background-color:green;' id="link1"><!-- Elsie --></a>
<a href="http://example.com/lacie" class="sister" id="link2">Lacie</a> and
<a href="http://example.com/tillie" class="sister" id="link3">Tilffffffffffffflie</a>;
and they lived at the bottom of a well.
<script>alert(123)</script>
</div>
</p>
<p class="story">...</p>"""
obj = XSSFilter()
v = obj.process(html)
print(v)
注意:
上方实例中kindEditor向后台提交数据的时候,用的是Form方式;其实,kindEditor也支持Ajex的方式提交,只是当Ajax提交表单时,textarea的value还是空的,需要使用sync()去同步HTML数据!
那么在什么时候去同步,怎么同步?KindEditor同时提供了方法:
afterBlur
编辑器失去焦点(blur)时执行的回调函数。
数据类型: Function
默认值: 无
解决办法:
<script type="text/javascript">
KindEditor.ready(function (K) {
window.editor = K.create('#AContent', {
afterBlur: function () { this.sync(); }
});
});
</script>
在使用Ajex方式向后台提交数据的时候,遇到问题的小伙伴,可以参考如下地址:
http://www.cnblogs.com/yuejin/p/3747331.html
http://www.cnblogs.com/nangong/p/e7e17fa4ab1a88af4046e828d5d4d243.html
kindEditor 使用的更多相关文章
- 让kindeditor显示高亮代码
kindeditor4.x代码高亮功能默认使用的是prettify插件,prettify是Google提供的一款源代码语法高亮着色器,它提供一种简单的形式来着色HTML页面上的程序代码,实现方式如下: ...
- Kindeditor在ThinkPHP框架下的使用
1.简单调用Kindeditor的图片上传功能: a.Html部署图片预览,记录图片上传成功之后的路径,以及上传图片点击按钮 <tr> <td>活动图片:</td> ...
- ASP.NET MVC5+EF6+EasyUI 后台管理系统(36)-文章发布系统③-kindeditor使用
系列目录 我相信目前国内富文本编辑器中KindEditor 属于前列,详细的中文帮助文档,简单的加载方式,可以定制的轻量级.都是系统的首选 很多文章教程有kindeditor的使用,但本文比较特别可能 ...
- KindEditor 给KindEditor赋值
在项目的过程中,使用了KindEditor编辑器,然后在赋值的时候,我的编辑器ID是content,然后我想通过$("#content").html()来赋值,发现赋值失败,后来百 ...
- Ajax 提交KindEditor的数据
这次我是在EasyUI中使用了KindEditor的编辑器,按照官方给的代码,总是无法获取编辑器里面的值(内容),如下: KindEditor.ready(function (K) { ...
- 如何在一个页面添加多个不同的kindeditor编辑器
kindeditor官方下载地址:http://kindeditor.net/down.php (入门必看)kindeditor官方文档:http://kindeditor.net/doc.ph ...
- kindeditor 去掉网络图片上传功能
kindeditor是一款开源的富文本编辑器,其内容设置均为可配置,使用比较灵活. 去掉网络图片的页面:allowImageRemote: false, 修改上传的图片的name:filePostNa ...
- 关于JqueryEasyUI集合Kindeditor
写在前面 上一篇<初试JqueryEasyUI(附Demo)>: 在上一篇说过,下面要试下easyui集合编辑器,关于编辑器网上有很多,ckeditor.ueditor.kindedito ...
- jquery弹出下拉列表插件(实现kindeditor的@功能)
这几天有个工作需求,就是在富文本输入区域(kindeditor)可以有@功能,能够容易提示用户名的(像在qq群组@人一样).在网上找了一个叫bootstrap-suggest的插件,却不能满足我的需求 ...
- kindeditor在光标处插入编辑器外的数据
页面 <div class="form-group clearfix"> <label class="control-label col-sm-3 co ...
随机推荐
- boost-智能指针
使用boost的智能指针需要包含头文件"boost/smart_ptr.hpp",c++11中需要包含头文件<memory> 1.auto_ptr.scoped_ptr ...
- matlab生成滤波器系数组
用MATLAB生成的滤波器系数是可以控制增益的,一般归一化的目的是控制增益为1.滤波器的阶数由数据速率,过渡带宽.通带波纹和阴带波纹来决定, 在下图中FS,Apass,Astop固定之后,只要Fpas ...
- 如何使用vs进行代码比较
当我们在进行团队合作开始项目时,有时候不仅自己要写代码还需要修改bug,当我们修改代码以后,为了保持代码库中代码的整洁美观和一直性,有些误操作,比如多一个或多个空格,多一行,少一行,格式对齐等,这样的 ...
- Ng第四课:多变量线性回归(Linear Regression with Multiple Variables)
4.1 多维特征 4.2 多变量梯度下降 4.3 梯度下降法实践 1-特征缩放 4.4 梯度下降法实践 2-学习率 4.5 特征和多项式回归 4.6 正规方程 4.7 正规方程及不可逆性 ...
- C++之引用和指针
作者:tongqingliu 转载请注明出处:http://www.cnblogs.com/liutongqing/p/7050431.html C++之引用和指针 C++引用 引用的基本用法: in ...
- web-day12
第12章WEB12-JSP&EL&JSTL篇 今日任务 商品信息的显示 教学导航 教学目标 掌握JSP的基本的使用 掌握EL的表达式的用法 掌握JSTL的常用标签的使用 教学方法 案例 ...
- lowbit(x)
int Lowbit(int x) { return x&(-x); } lowbit当中x,-x,补码,反码,傻傻分不清楚.我们先看看两个二进制数相减的问题 两个二进制数相减的相关问题 两个 ...
- ASP.NET MVC IActionFilter IResultFilter IExceptionFilter/HandleError
一.IActionFilter 1.基本定义 在action的执行前后进行AOP拦截. IActionFilter接口定义如下: public interface IActionFilter { // ...
- springmvc配置文件web.xml详解各方总结。
Spring分为多个文件进行分别的配置,其中在servlet-name中如果没有指定init-param属性,那么系统自动寻找的spring配置文件为[servlet-name]-servlet.xm ...
- 深度学习主机环境配置: Ubuntu16.04+GeForce GTX 1080+TensorFlow
接上文<深度学习主机环境配置: Ubuntu16.04+Nvidia GTX 1080+CUDA8.0>,我们继续来安装 TensorFlow,使其支持GeForce GTX 1080显卡 ...