一、kindeditor安装
- 普通使用
下载编辑器kindeditor最新版本
解压文件,然后将所有文件上传到工程目录下,具体目录视不同框架而定
在html页面引入以下js文件,路径需要修改为自己的路径,保证文件能正常加载
Bash
<script charset="utf-8" src="/editor/kindeditor.js"></script>
<script charset="utf-8" src="/editor/lang/zh-CN.js"></script>
在页面需要的部分加入textarea控件,注意:id需要唯一
Bash
<textarea id="editor_id" name="content" style="width:700px;height:300px;">
这里写入内容
</textarea>
最后需要增加以下js代码,用于初始化控件
Bash
<script>
//简单模式初始化
var editor;
var options = {};
KindEditor.ready(function(K) {
editor = K.create('#editor_id', options);
});
</script>
注意:
第一个参数为css选择器,一次只能初始化一个textarea元素。
options为编辑器的配置项,具体参数请参考官网
- rails安装
安装过程非常简单,首先在Gemfile
Bash
gem 'rails_kindeditor'
bundle install
然后执行命令生成相关文件
Bash
rails g rails_kindeditor:install
修改配置文件参数config/initializers/rails_kindeditor.rb,例如文件上传路径,上传文件类型等
Bash
RailsKindeditor.setup do |config|
# Specify the subfolders in public directory.
# You can customize it , eg: config.upload_dir = 'this/is/my/folder'
config.upload_dir = 'uploads'
# Allowed file types for upload.
config.upload_image_ext = %w[gif jpg jpeg png bmp]
config.upload_flash_ext = %w[swf flv]
config.upload_media_ext = %w[swf flv mp3 wav wma wmv mid avi mpg asf rm rmvb]
config.upload_file_ext = %w[doc docx xls xlsx ppt htm html txt zip rar gz bz2]
# Porcess upload image size
# eg: 1600x1600 => 800x800
# 1600x800 => 800x400
# 400x400 => 400x400 # No Change
# config.image_resize_to_limit = [800, 800]
# if you have config in your rails application like this:
# /config/enviroments/production.rb
# # config.action_controller.asset_host = "http://asset.example.com"
# # config.assets.prefix = "assets_prefx"
# then you should:
#
# config.asset_url_prefix = "http://asset.example.com/assets_prefx/" if Rails.env.production?
end
在view中嵌入编辑器
Bash
<%= kindeditor_tag :content,"这里是默认内容" %>
然后编辑器就可以使用,如图:
二、填坑
- 获取文本框内容
当表单提交时会发现,提交的数据并没有获取到文本框中的内容,这是因为输入数据时并不能实时使textarea获取到文本内容,那么我们就需要在提交表单时手动赋值
Bash
var editor = KindEditor.instances[0];
editor.sync();
注意,此处KindEditor.instances获取到的是一个文本框数组,根据自己需要取值
- 生产环境使用
rails生产环境都会使用production配置启动,首先需要编译资源文件
Bash
RAILS_ENV=production rake assets:precompile
但是当编译完之后,会发现KindEditor的样式文件并没有获取到,这是因为KindEditor需要单独编译
Bash
rails kindeditor:assets
这时public/assets下就出现了KindEditor需要的资源文件,KindEditor也可以正常使用。
本文暂时没有评论,来添加一个吧(●'◡'●)