一.基於javascript和css開發的 Web富文本編輯器, 輕量、簡潔、易用、開源免費
使用原因 wangeditor的文檔 (地址:http://www.wangeditor.com/)
1.輕量:相對於百度富文本,體積真心小,
2.簡潔:我的理解,功能剛剛夠用。使用wangeditor的項目,要對富文本的功能要求簡單。
安裝 npm 命令安裝 npm install wangeditor
(注意 wangeditor
全部是小寫字母)
二,wangeditor的使用
在不同環境中使用,寫法有點不同,但是文檔都有介紹 。https://www.kancloud.cn/wangfupeng/wangeditor3/335770
以下是本人在react中使用
render(){
return(
<div className="shop">
<div className="text-area" >
<div ref="editorElemMenu" style={{backgroundColor:'#f1f1f1',border:"1px solid #ccc"}} className="editorElem-menu"></div>
<div ref="editorElemBody" style={{padding:"0 10px",height:500,border:"1px solid #ccc",borderTop:"none"}} className="editorElem-body"></div>
</div>
<Button onClick={this.editorupdata.bind(this)}>提交添加</Button>
</div>
)
}
componentDidMount() {
const editorinfo = this.props.editorinfo;
const elemMenu = this.refs.editorElemMenu;
const elemBody = this.refs.editorElemBody;
const editor = new E(elemMenu,elemBody)
//拿到頁面首次圖片
this.firstimg();
// 使用 onchange 函數監聽內容的變化,並實時更新到 state 中
editor.customConfig.onchange = html => {
this.setState({
editorContent: editor.txt.html(),
})
this.selectdiffent()
}
editor.customConfig.menus = [
'head', // 標題
'bold', // 粗體
'fontSize', // 字號
'fontName', // 字體
'italic', // 斜體
'underline', // 下劃線
'strikeThrough', // 刪除線
'foreColor', // 文字顏色
'backColor', // 背景顏色
'link', // 插入鏈接
'list', // 列表
'justify', // 對齊方式
'quote', // 引用
'image', // 插入圖片
'table', // 表格
'undo', // 撤銷
'redo' // 重複
]
//使用Base64
// editor.customConfig.uploadImgShowBase64 = true
editor.create()
};
圖片上傳自定義(本人使用的axios請求)
editor.customConfig.customUploadImg = function (files, insert) {
// files 是 input 中選中的文件列表insert 是獲取圖片 url 後,插入到編輯器的方法
let file;
if (files && files.length) {
file = files[0];
} else {
return
}
// 圖片上傳
const formData = new FormData();
formData.append('file', file);
formData.append('Banners',{id:editorinfo.id,naviChildId:editorinfo.naviChildId})
axios.post('main/banners/addPhoto',formData,'ADMINUSER').then(res =>{
console.log(res)
})
//console.log(file,editorinfo)
//上傳成功之後把圖片插入到也買你中
//insert(imgUrl)
}
說一下自己遇到的問題
1.富文本內容回顯
<p dangerouslySetInnerHTML={{__html: this.props.editorinfo.titleRemark}}></p>
2.富文本圖片刪除
理論,每當富文本內容變化,對比出來圖片是否有減少,如果有就做刪除處理
//進入頁面查詢頁面上的所有圖片
firstimg = ()=>{
const diffent = []
var imgList = document.getElementsByTagName('img');
for(var i =0;i<imgList.length;i++){
diffent.push(imgList[i].namespaceURI)
}
this.setState({
imgList:diffent
})
}
// 查不同
selectdiffent = ()=>{
//獲取頁面最新圖片
const newimg = []
var imgList = document.getElementsByTagName('img');
for(var i =0;i<imgList.length;i++){
newimg.push(imgList[i].src)
}
// 跟頁面上的老圖片對比
var oldimg = this.state.imgList
var result =[];
if(newimg.length < oldimg.length){
var c=newimg.toString();
for(var j=0;j<oldimg.length;j++){
if(c.indexOf(oldimg[j].toString())===-1){
result.push(oldimg[j]);
}
}
axios.delete('後端地址').then(res =>{
if(res.code === 0){
message.success('圖片已刪除')
}
})
}
//更新頁面圖片
this.setState({
imgList:newimg
})
}
3.富文本樣式出現混亂
原因是css控制出現問題 input的class的block