百度ueditor富文本--PC端单个,PC端多个,mobile单个,mobile多个
我們在之前的文章中已經(jīng)做過富文本插件的調(diào)研。
富文本插件
Ueditor
是百度推出的一款開源在線 HTML 編輯器。
http://fex-team.github.io/ueditor/
比較好用,我們本章詳細(xì)記錄它的應(yīng)用過程,以及在不同場景下的具體配置。
我們在之前的文章中已經(jīng)在SpringMVC基礎(chǔ)框架的基礎(chǔ)上應(yīng)用了BootStrap的后臺框架,在此基礎(chǔ)上記錄?ueditor用法。
基礎(chǔ)項目源碼下載地址為:
SpringMVC+Shiro+MongoDB+BootStrap基礎(chǔ)框架
我們在基礎(chǔ)項目中已經(jīng)做好了首頁index的訪問。
現(xiàn)在就在index.jsp頁面和index的路由Controller上做修改,實現(xiàn) ?ueditor用法。
下載引用插件
ueditor可以定制,我們這里下載JSP版:
http://ueditor.baidu.com/website/download.html
http://download.csdn.net/detail/q383965374/9887681
下載到的zip包解壓后文件如圖,使用瀏覽器打開index.html有完整的demo。
我們在項目中webapp路徑下新建一個ueditor文件夾,把解壓出來的文件都放入其中,如圖:
引用方式如下:
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>ueditor.config.js是配置文件,可以在里面調(diào)整相關(guān)配置和工具欄工具。
PC端單個
我們現(xiàn)在來在index.jsp頁面中初始化一個富文本,富文本中錄入的內(nèi)容用于展示在PC端。
引入使用代碼
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>html中使用占位代碼
<script id="name" class="ueditorFlag" name="name" type="text/plain" style="width:100%;height:150px;"> ${pic.name}</script>初始化代碼,使用class名稱初始化
// 初始化文本編輯器 $(".ueditorFlag").each(function() {var id = this.id; var ue = UE.getEditor(id, {pasteplain: true, /* 純文本粘貼 */autoHeightEnabled:false,/* 啟用右側(cè)滾輪,默認(rèn)是true自動長高模式*/toolbars: [['fullscreen', 'source', '|', 'undo', 'redo', '|','bold', 'italic', 'underline','removeformat', '|','insertorderedlist', 'insertunorderedlist','indent', '|', 'justifyleft', 'justifycenter','|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', 'insertimage','|', 'link', 'unlink']]}).addOutputRule(function(root){// 每次編輯框獲取焦點(diǎn)的時候都會自動插入<p><br/></p> 不需要的話我們這里可以處理一下// 只處理第一個空的段落,后面的段落可能是人為添加var firstPNode = root.getNodesByTagName("p")[0];firstPNode && /^\s*(<br\/>\s*)?$/.test(firstPNode.innerHTML()) && firstPNode.parentNode.removeChild(firstPNode);});console.log('ueditor for ' + id + ' init.'); });用法與input一樣,即可以form提交也可以js中獲取值再提交,傳遞到后臺的參數(shù)名稱是 name的value。
完整html
<%@ include file="./include/header.jsp"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script><div id="page-wrapper"><div id="page-inner"><div class="row"><div class="col-md-12"><h1 class="page-header">ueditor用法 <small>PC端單個</small></h1></div></div><!-- /. ROW --><div class="tab-pane fade active in"><form id="base"><div><h4>名稱</h4><script id="name" class="ueditorFlag" name="name" type="text/plain" style="width:100%;height:150px;"> ${pic.name}</script></div><button type="button" class="btn btn-primary save">保存</button></form></div> <!-- /. ROW --></div><!-- /. PAGE INNER --></div><!-- /. PAGE WRAPPER --><%@ include file="./include/footer.jsp"%> <script type="text/javascript">// 初始化文本編輯器 $(".ueditorFlag").each(function() {var id = this.id; var ue = UE.getEditor(id, {pasteplain: true, /* 純文本粘貼 */autoHeightEnabled:false,/* 啟用右側(cè)滾輪,默認(rèn)是true自動長高模式*/toolbars: [['fullscreen', 'source', '|', 'undo', 'redo', '|','bold', 'italic', 'underline','removeformat', '|','insertorderedlist', 'insertunorderedlist','indent', '|', 'justifyleft', 'justifycenter','|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', 'insertimage','|', 'link', 'unlink']]}).addOutputRule(function(root){// 每次編輯框獲取焦點(diǎn)的時候都會自動插入<p><br/></p> 不需要的話我們這里可以處理一下// 只處理第一個空的段落,后面的段落可能是人為添加var firstPNode = root.getNodesByTagName("p")[0];firstPNode && /^\s*(<br\/>\s*)?$/.test(firstPNode.innerHTML()) && firstPNode.parentNode.removeChild(firstPNode);});console.log('ueditor for ' + id + ' init.'); });/*** jQuery form 擴(kuò)展獲取數(shù)據(jù)*/ $.fn.formGet = function(opts) { opts = $.extend({}, opts); var data = {},els = opts.formGroup ? this.find('[form-group="' + opts.formGroup + '"]') : this.find('[name]'); if (!els || !els.length) {return data; }var fnSetValue = (function(emptyToNull) {return emptyToNull ? function(obj, propertyChain, value, allowMulti) {value !== '' && _fnObjectSetPropertyChainValue(obj, propertyChain, value, allowMulti)} : _fnObjectSetPropertyChainValue })(opts.emptyToNull);els.each(function() {var $this = $(this),type = $this.attr('type'),name = $this.attr('name'), // 可能為屬性鏈tag = this.tagName.toLowerCase();if (tag == 'input') {if (type == 'checkbox') {var v = $(this).val();if (v == 'on' || !v) {fnSetValue(data, name, $(this).prop('checked'));} else {$(this).prop('checked') && fnSetValue(data, name, v, true);}} else if (type == 'radio') {this.checked && fnSetValue(data, name, $this.val());} else {fnSetValue(data, name, $this.val());}} else if ('|select|textarea|'.indexOf('|' + tag + '|') > -1) {fnSetValue(data, name, $this.val());} else {fnSetValue(data, name, $.trim($this.text()));} }); return data; };/** * 內(nèi)部私有方法 */ var _fnObjectGetPropertyChainValue = function(obj, propertyChain) { /* 獲取屬性鏈的值 */ if (!obj) return; if (!propertyChain) return obj; var property, chains = propertyChain.split('.'), i = 0, len = chains.length; for (; (property = chains[i]) && i < len - 1; i++) { if (!obj[property]) return; obj = obj[property]; } return obj[property]; }, _fnObjectSetPropertyChainValue = function(obj, propertyChain, value, allowMulti) { /* 設(shè)置屬性鏈的值 */ if (!obj || !propertyChain) return; var property, chainObj = obj, chains = propertyChain.split('.'), i = 0, len = chains.length; for (; (property = chains[i]) && i < len - 1; i++) { if (!chainObj[property]) { chainObj[property] = {}; } chainObj = chainObj[property]; } // 改進(jìn)版:checkbox的多選可以組合為數(shù)組 if (!allowMulti || chainObj[property] === undefined) { chainObj[property] = value; } else { var pv = chainObj[property]; if ($.isArray(pv)) { pv.push(value); } else { chainObj[property] = [pv, value]; } } return obj; }; $(document).ready(function () {/*END-保存表單-END*/$('button.save').on('click', function () {debugger;var data = $('#base').formGet();$.ajax({type: "POST",url: "/pic/save",contentType: "application/json",data: JSON.stringify(data),success: function (result) {console.log(result);if (!result.code) {alert(result.data);} else {alert(result.msg);}},error: function (result) {alert("出錯了,請稍后重試");}});});});</script></body></html>輔助實體和路由
Pic.java
package com.test.domain.entity;import java.util.List;public class Pic {private String id;private String name;private String description;private List<String> tags;//標(biāo)簽public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public List<String> getTags() {return tags;}public void setTags(List<String> tags) {this.tags = tags;}}IndexController.java
package com.test.web.controller;import java.io.IOException; import java.util.ArrayList; import java.util.List;import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;import com.test.domain.entity.Pic; import com.test.util.JSONResult;/*** IndexController* * */ @Controller public class IndexController {@RequestMapping("/")public String index(Model model) throws IOException {model.addAttribute("hostname", "http://127.0.0.1:8080/");Pic pic=new Pic();List<String> tags=new ArrayList<String>();pic.setName("name");pic.setDescription("描述");tags.add("足球");tags.add("棒球");tags.add("籃球");pic.setTags(tags);model.addAttribute("pic", pic);return "/index";}@RequestMapping("/pic/save")@ResponseBodypublic JSONResult saveMigrateLine(@RequestBody Pic pic) {//保存pic記錄//int result = save(pic);int result =1;return result > 0 ? JSONResult.success("保存成功"):JSONResult.error("保存失敗!");} }PC端多個
因為我們這里是使用class進(jìn)行初始化的,所以要增加多一個輸入框的時候非常簡單,只需要增加一個 同樣class的占位代碼即可。如下:
它們的class都是ueditorFlag。
? ? ? ? ? <h4>名稱</h4><script id="name" class="ueditorFlag" name="name" type="text/plain" style="width:100%;height:150px;"> ${pic.name}</script><h4>描述</h4><script id="description" class="ueditorFlag" name="description" type="text/plain" style="width:100%;height:150px;"> ${pic.description}</script>需要注意的是 使用多個script作為占位時,script的id不能與html中的其他元素 id重復(fù) ,否則頁面布局會混亂。
mobile單個
之前的單個和多個都是針對PC版使用時的初始化,現(xiàn)在微信公眾號文章和手機(jī)端的編輯也是很常用的。 為了可以在頁面上更真實的模擬 文本在mobile上的顯示是否美觀,我們對ueditor的樣式在初始化時進(jìn)行了一些樣式調(diào)整。 尤其是加上寬度的限制即可。
style="width:375px;height:667px;"引入使用代碼
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>html中使用占位代碼
<script id="content" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"name="content"></script>初始化代碼,使用class名稱初始化
function () {$(".ueditorFlag").each(function () {//實例化編輯器var ue = UE.getEditor(this.id, {pasteplain: true, /* 純文本粘貼 */toolbars: [['fullscreen', 'source', '|', 'undo', 'redo', '|','bold', 'italic', 'underline', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', /*'selectall', 'cleardoc',*/ '|','rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontsize', '|', 'indent', '|','justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', '|','link', 'unlink', /*'anchor'*/, '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|','insertimage', 'preview', '|', 'foreword', 'subhead', 'body', 'caption', 'stress', 'quote']],iframeCssUrl: "/ueditor/themes/ancestry.css"});ue.ready(function() {ue.setContent('${pic.description}');});});}用法與input一樣,即可以form提交也可以js中獲取值再提交,傳遞到后臺的參數(shù)名稱是 name的value。
完整html
<%@ include file="./include/header.jsp"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %><script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script><div id="page-wrapper"><div id="page-inner"><div class="row"><div class="col-md-12"><h1 class="page-header">ueditor用法 <small>mobile端單個</small></h1></div></div><!-- /. ROW --><div class="tab-pane fade active in"><form id="base"><div><h4>內(nèi)容</h4><script id="content" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"name="content"></script></div><button type="button" class="btn btn-primary save">保存</button></form></div> <!-- /. ROW --></div><!-- /. PAGE INNER --></div><!-- /. PAGE WRAPPER --><%@ include file="./include/footer.jsp"%> <script type="text/javascript">$(document).ready(function () {$(".ueditorFlag").each(function () {//實例化編輯器var ue = UE.getEditor(this.id, {pasteplain: true, /* 純文本粘貼 */toolbars: [['fullscreen', 'source', '|', 'undo', 'redo', '|','bold', 'italic', 'underline', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', /*'selectall', 'cleardoc',*/ '|','rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontsize', '|', 'indent', '|','justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', '|','link', 'unlink', /*'anchor'*/, '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|','insertimage', 'preview', '|', 'foreword', 'subhead', 'body', 'caption', 'stress', 'quote']],iframeCssUrl: "/ueditor/themes/ancestry.css"});ue.ready(function() {ue.setContent('${pic.description}');});});} )/*** jQuery form 擴(kuò)展獲取數(shù)據(jù)*/ $.fn.formGet = function(opts) { opts = $.extend({}, opts); var data = {},els = opts.formGroup ? this.find('[form-group="' + opts.formGroup + '"]') : this.find('[name]'); if (!els || !els.length) {return data; }var fnSetValue = (function(emptyToNull) {return emptyToNull ? function(obj, propertyChain, value, allowMulti) {value !== '' && _fnObjectSetPropertyChainValue(obj, propertyChain, value, allowMulti)} : _fnObjectSetPropertyChainValue })(opts.emptyToNull);els.each(function() {var $this = $(this),type = $this.attr('type'),name = $this.attr('name'), // 可能為屬性鏈tag = this.tagName.toLowerCase();if (tag == 'input') {if (type == 'checkbox') {var v = $(this).val();if (v == 'on' || !v) {fnSetValue(data, name, $(this).prop('checked'));} else {$(this).prop('checked') && fnSetValue(data, name, v, true);}} else if (type == 'radio') {this.checked && fnSetValue(data, name, $this.val());} else {fnSetValue(data, name, $this.val());}} else if ('|select|textarea|'.indexOf('|' + tag + '|') > -1) {fnSetValue(data, name, $this.val());} else {fnSetValue(data, name, $.trim($this.text()));} }); return data; };/** * 內(nèi)部私有方法 */ var _fnObjectGetPropertyChainValue = function(obj, propertyChain) { /* 獲取屬性鏈的值 */ if (!obj) return; if (!propertyChain) return obj; var property, chains = propertyChain.split('.'), i = 0, len = chains.length; for (; (property = chains[i]) && i < len - 1; i++) { if (!obj[property]) return; obj = obj[property]; } return obj[property]; }, _fnObjectSetPropertyChainValue = function(obj, propertyChain, value, allowMulti) { /* 設(shè)置屬性鏈的值 */ if (!obj || !propertyChain) return; var property, chainObj = obj, chains = propertyChain.split('.'), i = 0, len = chains.length; for (; (property = chains[i]) && i < len - 1; i++) { if (!chainObj[property]) { chainObj[property] = {}; } chainObj = chainObj[property]; } // 改進(jìn)版:checkbox的多選可以組合為數(shù)組 if (!allowMulti || chainObj[property] === undefined) { chainObj[property] = value; } else { var pv = chainObj[property]; if ($.isArray(pv)) { pv.push(value); } else { chainObj[property] = [pv, value]; } } return obj; }; $(document).ready(function () {/*END-保存表單-END*/$('button.save').on('click', function () {debugger;var data = $('#base').formGet();$.ajax({type: "POST",url: "/pic/save",contentType: "application/json",data: JSON.stringify(data),success: function (result) {console.log(result);if (!result.code) {alert(result.data);} else {alert(result.msg);}},error: function (result) {alert("出錯了,請稍后重試");}});});});</script></body></html>輔助實體和路由
Pic.java
package com.test.domain.entity;import java.util.List;public class Pic {private String id;private String name;private String description;private List<String> tags;//標(biāo)簽public String getId() {return id;}public void setId(String id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getDescription() {return description;}public void setDescription(String description) {this.description = description;}public List<String> getTags() {return tags;}public void setTags(List<String> tags) {this.tags = tags;}}IndexController.java
package com.test.web.controller;import java.io.IOException; import java.util.ArrayList; import java.util.List;import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody;import com.test.domain.entity.Pic; import com.test.util.JSONResult;/*** IndexController* * */ @Controller public class IndexController {@RequestMapping("/")public String index(Model model) throws IOException {model.addAttribute("hostname", "http://127.0.0.1:8080/");Pic pic=new Pic();List<String> tags=new ArrayList<String>();pic.setName("name");pic.setDescription("描述");tags.add("足球");tags.add("棒球");tags.add("籃球");pic.setTags(tags);model.addAttribute("pic", pic);return "/index";}@RequestMapping("/pic/save")@ResponseBodypublic JSONResult saveMigrateLine(@RequestBody Pic pic) {//保存pic記錄//int result = save(pic);int result =1;return result > 0 ? JSONResult.success("保存成功"):JSONResult.error("保存失敗!");} }效果圖
mobile多個
mobile多個跟PC多個一樣,使用class來初始化即可。 給每個編輯框限制寬度。
style="width:375px;height:667px;"
引用插件
<script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.config.js"></script> <script type="text/javascript" charset="utf-8" src="/ueditor/ueditor.all.min.js"></script>html占位
<div class="tab-pane fade active in"><form id="base"><div><h4>內(nèi)容</h4><script id="name" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"name="name">${pic.name}</script></div><div><h4>描述</h4><script id="description" class="ueditorFlag" type="text/plain" style="width:375px;height:667px;"name="description">${pic.description}</script></div><button type="button" class="btn btn-primary save">保存</button></form></div>初始化代碼
$(document).ready(function () {$(".ueditorFlag").each(function () {//實例化編輯器var ue = UE.getEditor(this.id, {pasteplain: true, /* 純文本粘貼 */toolbars: [['fullscreen', 'source', '|', 'undo', 'redo', '|','bold', 'italic', 'underline', 'removeformat', 'formatmatch', 'autotypeset', 'blockquote', 'pasteplain', '|', 'forecolor', 'backcolor', 'insertorderedlist', 'insertunorderedlist', /*'selectall', 'cleardoc',*/ '|','rowspacingtop', 'rowspacingbottom', 'lineheight', '|', 'fontsize', '|', 'indent', '|','justifyleft', 'justifycenter', 'justifyright', 'justifyjustify', '|', '|','link', 'unlink', /*'anchor'*/, '|', 'imagenone', 'imageleft', 'imageright', 'imagecenter', '|','insertimage', 'preview', '|', 'foreword', 'subhead', 'body', 'caption', 'stress', 'quote']]});});} )完整html代碼
其他輔助類參考上文。
效果如圖:
總結(jié)
以上是生活随笔為你收集整理的百度ueditor富文本--PC端单个,PC端多个,mobile单个,mobile多个的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ch340串口驱动_如何使用串口来给ST
- 下一篇: 早期股权分配不是有钱就能搞定的!