010.UEditor文檔

UEditor的簡單使用

在Java Web階段和SSM框架階段,我們的課程設(shè)計中都會使用到富文本編輯器,目前流行的編輯器很多

KindEditor/CKEditor/UEditor/WangEditor等,這里我們使用的是百度開源的,這里我們使用JSP的版本

這部分屬于自學(xué)內(nèi)容,請各位同學(xué)根據(jù)文檔完成下面配置過程

1.下載UEditor

網(wǎng)址: http://ueditor.baidu.com/website/download.html

image

2.新建動態(tài)的Web項目

因為我使用的是SpringMVC框架,如果使用Java Web階段是比較簡單的.

請注意要排除靜態(tài)資源

<!-- 4.1 靜態(tài)資源排除方案1 -->
<mvc:default-servlet-handler default-servlet-name="default"/>

將下載的文檔解壓后,復(fù)制到WebContent的resource文件夾下,如圖所示:

image

3.顯示富文本編輯器

  • 添加UEditor需要的Jar包

    image

    將紅色部分的jar包復(fù)制添加到WEB-INF/lib下

  • 顯示富文本編輯器

    根據(jù)示例中的index.html或者官方文檔給的示例,將富文本編輯器進(jìn)行顯示,因為我們將所有的JSP都放置到WEB-INF文件夾

    • 新建Controller完成跳轉(zhuǎn)

      @Controller
      public class TestController {
          @GetMapping("/show")
          public String showUE(){
              return "jsp/ueditor";
          }
      }
      
    • 顯示富文本編輯器ueditor.jsp

      <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
      <%
          String path = request.getContextPath();
          String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
      %>
      <!DOCTYPE HTML>
      <html>
          <head>
              <base href="<%=basePath%>">
              <meta charset="UTF-8">
              <title>富文本編輯器</title>
              <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.config.js"></script>
              <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.all.min.js"> </script>
              <!--建議手動加在語言,避免在ie下有時因為加載語言失敗導(dǎo)致編輯器加載失敗-->
              <!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
              <script type="text/javascript" charset="utf-8" src="resource/ueditor/lang/zh-cn/zh-cn.js"></script>
              <style type="text/css">
                  div{
                      width:100%;
                  }
              </style>
      </head>
      <body>
          <div>
              <h1>完整demo</h1>
              <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
          </div>
          <div id="btns">
              <div>
                  <button onclick="getAllHtml()">獲得整個html的內(nèi)容</button>
                  <button onclick="getContent()">獲得內(nèi)容</button>
                  <button onclick="setContent()">寫入內(nèi)容</button>
                  <button onclick="setContent(true)">追加內(nèi)容</button>
                  <button onclick="getContentTxt()">獲得純文本</button>
                  <button onclick="getPlainTxt()">獲得帶格式的純文本</button>
                  <button onclick="hasContent()">判斷是否有內(nèi)容</button>
                  <button onclick="setFocus()">使編輯器獲得焦點</button>
                  <button onmousedown="isFocus(event)">編輯器是否獲得焦點</button>
                  <button onmousedown="setblur(event)" >編輯器失去焦點</button>
          
              </div>
              <div>
                  <button onclick="getText()">獲得當(dāng)前選中的文本</button>
                  <button onclick="insertHtml()">插入給定的內(nèi)容</button>
                  <button id="enable" onclick="setEnabled()">可以編輯</button>
                  <button onclick="setDisabled()">不可編輯</button>
                  <button onclick=" UE.getEditor('editor').setHide()">隱藏編輯器</button>
                  <button onclick=" UE.getEditor('editor').setShow()">顯示編輯器</button>
                  <button onclick=" UE.getEditor('editor').setHeight(300)">設(shè)置高度為300默認(rèn)關(guān)閉了自動長高</button>
              </div>
          
              <div>
                  <button onclick="getLocalData()" >獲取草稿箱內(nèi)容</button>
                  <button onclick="clearLocalData()" >清空草稿箱</button>
              </div>
          
          </div>
          <div>
              <button onclick="createEditor()">
              創(chuàng)建編輯器</button>
              <button onclick="deleteEditor()">
              刪除編輯器</button>
          </div>
          
          <script type="text/javascript">
          
              //實例化編輯器
              //建議使用工廠方法getEditor創(chuàng)建和引用編輯器實例,如果在某個閉包下引用該編輯器,直接調(diào)用UE.getEditor('editor')就能拿到相關(guān)的實例
              var ue = UE.getEditor('editor');
          
          
              function isFocus(e){
                  alert(UE.getEditor('editor').isFocus());
                  UE.dom.domUtils.preventDefault(e)
              }
              function setblur(e){
                  UE.getEditor('editor').blur();
                  UE.dom.domUtils.preventDefault(e)
              }
              function insertHtml() {
                  var value = prompt('插入html代碼', '');
                  UE.getEditor('editor').execCommand('insertHtml', value)
              }
              function createEditor() {
                  enableBtn();
                  UE.getEditor('editor');
              }
              function getAllHtml() {
                  alert(UE.getEditor('editor').getAllHtml())
              }
              function getContent() {
                  var arr = [];
                  arr.push("使用editor.getContent()方法可以獲得編輯器的內(nèi)容");
                  arr.push("內(nèi)容為:");
                  arr.push(UE.getEditor('editor').getContent());
                  alert(arr.join("\n"));
              }
              function getPlainTxt() {
                  var arr = [];
                  arr.push("使用editor.getPlainTxt()方法可以獲得編輯器的帶格式的純文本內(nèi)容");
                  arr.push("內(nèi)容為:");
                  arr.push(UE.getEditor('editor').getPlainTxt());
                  alert(arr.join('\n'))
              }
              function setContent(isAppendTo) {
                  var arr = [];
                  arr.push("使用editor.setContent('歡迎使用ueditor')方法可以設(shè)置編輯器的內(nèi)容");
                  UE.getEditor('editor').setContent('歡迎使用ueditor', isAppendTo);
                  alert(arr.join("\n"));
              }
              function setDisabled() {
                  UE.getEditor('editor').setDisabled('fullscreen');
                  disableBtn("enable");
              }
          
              function setEnabled() {
                  UE.getEditor('editor').setEnabled();
                  enableBtn();
              }
          
              function getText() {
                  //當(dāng)你點擊按鈕時編輯區(qū)域已經(jīng)失去了焦點,如果直接用getText將不會得到內(nèi)容,所以要在選回來,然后取得內(nèi)容
                  var range = UE.getEditor('editor').selection.getRange();
                  range.select();
                  var txt = UE.getEditor('editor').selection.getText();
                  alert(txt)
              }
          
              function getContentTxt() {
                  var arr = [];
                  arr.push("使用editor.getContentTxt()方法可以獲得編輯器的純文本內(nèi)容");
                  arr.push("編輯器的純文本內(nèi)容為:");
                  arr.push(UE.getEditor('editor').getContentTxt());
                  alert(arr.join("\n"));
              }
              function hasContent() {
                  var arr = [];
                  arr.push("使用editor.hasContents()方法判斷編輯器里是否有內(nèi)容");
                  arr.push("判斷結(jié)果為:");
                  arr.push(UE.getEditor('editor').hasContents());
                  alert(arr.join("\n"));
              }
              function setFocus() {
                  UE.getEditor('editor').focus();
              }
              function deleteEditor() {
                  disableBtn();
                  UE.getEditor('editor').destroy();
              }
              function disableBtn(str) {
                  var div = document.getElementById('btns');
                  var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
                  for (var i = 0, btn; btn = btns[i++];) {
                      if (btn.id == str) {
                          UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
                      } else {
                          btn.setAttribute("disabled", "true");
                      }
                  }
              }
              function enableBtn() {
                  var div = document.getElementById('btns');
                  var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
                  for (var i = 0, btn; btn = btns[i++];) {
                      UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
                  }
              }
          
              function getLocalData () {
                  alert(UE.getEditor('editor').execCommand( "getlocaldata" ));
              }
          
              function clearLocalData () {
                  UE.getEditor('editor').execCommand( "clearlocaldata" );
                  alert("已清空草稿箱")
              }
          </script>
      </body>
      </html>
      
    • 代碼說明

      引入UEditor的庫

      <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.config.js"></script>
      <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.all.min.js"> </script>
      <script type="text/javascript" charset="utf-8" src="resource/ueditor/lang/zh-cn/zh-cn.js"></script>
      

      顯示編輯器的標(biāo)簽,這個標(biāo)簽跟以往的標(biāo)簽不一樣,但是最終的目的也是會生成textarea標(biāo)簽

      <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
      

      id很重要,會根據(jù)id進(jìn)行對富文本編輯器的渲染,代碼如下

      //實例化編輯器
      var ue = UE.getEditor('editor');
      
      image
      image

      但是這個時候,圖片功能無法使用,需要修改一下配置

      resource/ueditor/jsp/config.json需要修改里面的前綴 /mvc為發(fā)布路徑

      "imageUrlPrefix": "/mvc",

      "scrawlUrlPrefix": "/mvc",

      "snapscreenUrlPrefix": "/mvc",

      "catcherUrlPrefix": "/mvc",

      "videoUrlPrefix": "/mvc",

      "fileUrlPrefix": "/mvc",

      "imageManagerUrlPrefix": "/mvc",

      "fileManagerUrlPrefix": "/mvc",

      image

4.自定義風(fēng)格

  • 定制工具欄圖標(biāo)

    請參考官方文檔: http://fex.baidu.com/ueditor/#start-toolbar

    <div>
      <h1>完整demo</h1>
      <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
    </div>
    
    <script type="text/javascript">
      //實例化編輯器
      var ue = UE.getEditor('editor',{
        toolbars: [
          ['blockquote', 'bold','italic','underline','|', 'strikethrough','subscript','fontborder', 'superscript','|','justifyleft','justifyright', 'justifycenter','justifyjustify','spechars','emotion' ],
          ['insertcode','fontfamily','fontsize','forecolor','backcolor','|','simpleupload','insertimage',]
        ]
      });
    </script>
    
    image
  • 其他配置說明

    autoHeightEnabled {Boolean} [默認(rèn)值:true] //是否自動長高,默認(rèn)true

    autoFloatEnabled [默認(rèn)值:true] //是否保持toolbar的位置不動,默認(rèn)true

    initialContent {String} [默認(rèn)值:'歡迎使用ueditor!'] //初始化編輯器的內(nèi)容,

    initialFrameWidth {Number} [默認(rèn)值:1000] //初始化編輯器寬度,默認(rèn)1000

    initialFrameHeight {Number} [默認(rèn)值:320] //初始化編輯器高度,默認(rèn)320

    參考網(wǎng)址: http://fex.baidu.com/ueditor/#start-config

      <div>
          <h1>完整demo</h1>
          <script id="editor" type="text/plain" ></script>
      </div>
      
      <script type="text/javascript">
          //實例化編輯器
          var ue = UE.getEditor('editor',{
              toolbars: [
                  ['blockquote', 'bold','italic','underline','|', 'strikethrough','subscript','fontborder', 'superscript','|','justifyleft','justifyright', 'justifycenter','justifyjustify','spechars','emotion' ],
                  ['insertcode','fontfamily','fontsize','forecolor','backcolor','|','simpleupload','insertimage',]
              ],
              autoHeightEnabled:false,
              initialContent:"胖先森帶你學(xué)習(xí)",
              initialFrameWidth:700,
              initialFrameHeight:400
          });
      </script>
    

5.代碼高亮顯示

JSP頁面設(shè)置提交表單

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%
    //項目的發(fā)布路徑,例如:  /rabc
    String path = request.getContextPath();
    /*
    全路徑,形式如下: http://127.0.0.1:8001/rbac/
    request.getScheme()      ——> http 獲取協(xié)議
    request.getServerName()  --> 127.0.0.1 獲取服務(wù)名
    request.getServerPort()  --> 8001 獲取端口號
    path                     --> /rbac 獲取訪問的路徑 路
    */
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML>
<html>
    <head>
        <base href="<%=basePath%>">
        <meta charset="UTF-8">
        <title>H5模版:</title>
        <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.config.js"></script>
        <script type="text/javascript" charset="utf-8" src="resource/ueditor/ueditor.all.min.js"> </script>
        <!--建議手動加在語言,避免在ie下有時因為加載語言失敗導(dǎo)致編輯器加載失敗-->
        <!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
        <script type="text/javascript" charset="utf-8" src="resource/ueditor/lang/zh-cn/zh-cn.js"></script>
        <style type="text/css">
            div{
                width:100%;
            }
        </style>
</head>
<body>
    <form action="add" method="post">
    <div>
        <h1>完整demo</h1>
        <script id="editor" type="text/plain" name="content" ></script>
    </div>
    <button>提交數(shù)據(jù)顯示高亮顯示</button>
    </form>
    
    
    <script type="text/javascript">
        //實例化編輯器
        var ue = UE.getEditor('editor',{
            toolbars: [
                ['blockquote', 'bold','italic','underline','|', 'strikethrough','subscript','fontborder', 'superscript','|','justifyleft','justifyright', 'justifycenter','justifyjustify','spechars','emotion' ],
                ['insertcode','fontfamily','fontsize','forecolor','backcolor','|','simpleupload','insertimage',]
            ],
            autoHeightEnabled:false,
            initialContent:"胖先森帶你學(xué)習(xí)",
            initialFrameWidth:700,
            initialFrameHeight:400
        });
    </script>
</body>
</html>

Controller獲取數(shù)據(jù)

@Controller
public class TestController {

    @GetMapping("/show")
    public String showUE(){
        return "jsp/ueditor";
    }

    @PostMapping("/add")
    public String add(String content,Model model){
        model.addAttribute("content", content);
        return "jsp/show";
    }
}

show.jsp顯示高亮的代碼

引入高亮顯示的css和js庫,渲染

<html>
    <head>
        <base href="<%=basePath%>">
        <meta charset="UTF-8">
        <title>H5模版:</title>
        <link href="resource/ueditor/third-party/SyntaxHighlighter/shCoreDefault.css" rel="stylesheet" type="text/css" />
        <script type="text/javascript" src="resource/ueditor/third-party/SyntaxHighlighter/shCore.js"></script>
    </head>
    <body>
        <p>
          ${content }
        </p>
    <script type="text/javascript">
    SyntaxHighlighter.all();
    </script>
    </body>
</html>
image

備注修改了controller.jsp,需要注意工作空間和tomcat中不能含有中文,否則在線管理不好用

<%@ page language="java" contentType="text/html; charset=UTF-8"
    import="com.baidu.ueditor.ActionEnter"
    pageEncoding="UTF-8"%>
<%@ page trimDirectiveWhitespaces="true" %>
<%

    request.setCharacterEncoding( "utf-8" );
    response.setHeader("Content-Type" , "text/html");
    
    String rootPath = application.getRealPath( "/" );
    String action = request.getParameter("action"); 
    String result = new ActionEnter( request, rootPath ).exec() ;
    
    if( action!=null && (action.equals("listfile") || action.equals("listimage") ) ){  
                rootPath = rootPath.replace("\\", "/");  
                System.out.println("rootPath:"+rootPath);
                result = result.replaceAll(rootPath, "/");  
                System.out.println("result:"+result);
    }  
    out.write( result );
    
%>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 文章分類 后臺文章分類列表頁模板導(dǎo)的詳細(xì)步驟建立數(shù)據(jù)表blog_category,并添加相應(yīng)的文章字段使用php ...
    JoyceZhao閱讀 1,870評論 0 14
  • @轉(zhuǎn)自GitHub 介紹js的基本數(shù)據(jù)類型。Undefined、Null、Boolean、Number、Strin...
    YT_Zou閱讀 1,342評論 0 0
  • 以下是常用的代碼收集,學(xué)習(xí)用。轉(zhuǎn)自豪情博客園 1. PC - js 返回指定范圍的隨機(jī)數(shù)(m-n之間)的公式 re...
    自由加咖啡閱讀 1,131評論 0 1
  • 1.背景介紹 在做Web應(yīng)用時,經(jīng)常會進(jìn)行富文本編輯,常用的富文本編輯器有很多,比如CuteEditor、CKEd...
    維克拉瑪?shù)賮?/span>閱讀 2,327評論 0 0
  • 文、畫/云塵 首先,不管你是創(chuàng)作還是臨摹,尋找素材都是有必要的。哪怕你只是畫個蘋果,也是可以嚴(yán)謹(jǐn)?shù)娜フ覐埶夭膩韰⒄?..
    云影拂塵閱讀 913評論 28 38

友情鏈接更多精彩內(nèi)容