ASP.NET中UEditor使用
UEditor是由百度WEB前端研發部開發的所見即所得的開源富文本編輯器,具有輕量、可定制、用戶體驗優秀等特點。開源基於BSD協議,所有源代碼在協議允許范圍內可自由修改和使用。
UEditor官網:http://ueditor.baidu.com/website/index.html
UEditor官方文檔地址: http://fex.baidu.com/ueditor/
將從官網上下載的開發包解壓后包含到項目中
(注:最新的代碼需要時基於.NETFramework4以上)
解壓后目錄下文件如下:
index.html 是一個示例文件、可以刪去,ueditor.config.js中是一些富文本編輯器的設置,建議不要改動,可以在頁面中引用的時候設置,如果所有頁面都需要設置可以寫在一個js文件中,dialogs是在文本框中點擊按鈕時用到的一些彈出框效果,lang文件夾下是語言相關的設置,目前只有中文與英文,themes文件夾下是一些樣式,third-party文件夾下是一些第三方的插件,有代碼高亮,截屏等

我在我的項目中新建了一個ueditorHelper.js文件,在文件中定義了一些ueditor常用的方法,以及對於ueditor的一些設置


在net目錄下,我們只保留controller.ashx與config.json就可以了,同時把App_Code中的代碼拷貝到項目中的App_Code中,同時添加對bin目錄下Json.NET程序集的引用,config.json文件定義了一些設置,配置上傳文件的一些要求以及上傳到服務器保存的路徑,在web.config文件中可以看到項目框架應至少為4.0

添加zh-cn.js文件是要設置語言,防止自動識別語言錯誤而導致語言適配錯誤,UEditorHelper.js文件是一些常用的方法和編輯器設置的封裝,查看index.html的源代碼,在其中有一段js代碼

自定義的UEditorHelper.js文件中使用到了一些方法,並對第一行代碼進行了修改,進行 ueditor富文本編輯器的設置

3.頁面初始化
在需要添加富文本編輯器的地方加入以下代碼:
<script id="editor" type="text/plain"></script>
因為富文本編輯器只是生成的一段html代碼,我們需要利用Ajax動態加載內容,相比CKEditor來說,這是比較麻煩的地方,使用CKEditor可以直接使用封裝好的服務器端控件,當然也可以不用服務器端控件利用Ajax動態加載內容。
首先在頁面加載時獲取到新聞的id,然后再進行ajax查詢,查詢新聞封裝在了一個handler中,向這個handler發起ajax請求,請求參數為新聞id,獲取新聞,獲取到之后,把新聞的內容設置給ueditor

1 //實例化編輯器 2 //建議使用工廠方法getEditor創建和引用編輯器實例,如果在某個閉包下引用該編輯器,直接調用UE.getEditor('editor')就能拿到相關的實例 3 var ue = UE.getEditor('editor',{autoHeightEnabled: false}); 4 function isFocus(e) { 5 alert(UE.getEditor('editor').isFocus()); 6 UE.dom.domUtils.preventDefault(e) 7 } 8 function setblur(e) { 9 UE.getEditor('editor').blur(); 10 UE.dom.domUtils.preventDefault(e) 11 } 12 function insertHtml() { 13 var value = prompt('插入html代碼', ''); 14 UE.getEditor('editor').execCommand('insertHtml', value) 15 } 16 function createEditor() { 17 UE.getEditor('editor'); 18 } 19 function getAllHtml() { 20 return UE.getEditor('editor').getAllHtml(); 21 } 22 function getContent() { 23 return UE.getEditor('editor').getContent(); 24 } 25 function getPlainTxt() { 26 return UE.getEditor('editor').getPlainTxt(); 27 } 28 function setContent(isAppendTo) { 29 UE.getEditor('editor').setContent('', isAppendTo); 30 } 31 function getText() { 32 //當你點擊按鈕時編輯區域已經失去了焦點,如果直接用getText將不會得到內容,所以要在選回來,然后取得內容 33 var range = UE.getEditor('editor').selection.getRange(); 34 range.select(); 35 return UE.getEditor('editor').selection.getText(); 36 } 37 function getContentTxt() { 38 return UE.getEditor('editor').getContentTxt(); 39 } 40 function hasContent() { 41 return UE.getEditor('editor').hasContents(); 42 } 43 function setFocus() { 44 UE.getEditor('editor').focus(); 45 } 46 function deleteEditor() { 47 UE.getEditor('editor').destroy(); 48 } 49 function getLocalData() { 50 alert(UE.getEditor('editor').execCommand("getlocaldata")); 51 } 52 function clearLocalData() { 53 UE.getEditor('editor').execCommand("clearlocaldata"); 54 alert("已清空草稿箱") 55 }
