一、說明css
在angular項目中,須要實現相似於富文本編輯器的將選中的文字高亮顯示,並能夠取消高亮,引入富文本編輯器(ckeditor或ueditor)均可實現,可是有點大材小用,因此考慮寫一個輸入框,一個標註按鈕和一個取消標註的按鈕實現該功能。html
![](http://static.javashuo.com/static/loading.gif)
二、實現設計模式
1)在html中添加iframe編輯器
<iframe id='errEdit' (mouseout)="leaveIframe()"></iframe>字體 注:其中的mouseout事件是爲了監測內容輸入(blur事件不起做用)。優化 |
2)在ts中初始化並實現相關操做this
const erriframe = document.getElementById("errEdit"); if(!isNull(erriframe)) { // 沒有判斷剛進入時會報錯 this.errWindow = (<HTMLIFrameElement > erriframe).contentWindow; this.errdoc = (<HTMLIFrameElement > erriframe).contentDocument; this.errWindow.document.designMode = 'On'; // 打開設計模式 this.errWindow.document.contentEditable = true; // 設置元素爲可編輯 this.errWindow.document.body.style.fontSize = 14 + 'px'; // 初始化字體大小 //this.errWindow.document.body.style.cssText = "font-size:14px;line-height:16px;"; // 設置多個樣式 } // 標註 markErrConfirm() { this.errWindow.document.execCommand('BackColor',true,'yellow'); this.errWindow.document.execCommand('ForeColor',true,'red') } // 取消標註 cancelErrMark() { this.errWindow.document.execCommand("RemoveFormat",false,null); this.errWindow.document.body.style.fontSize = 14 + 'px'; // 由於上面一句將修改的iframe樣式所有重置,因此須要對須要的樣式從新設置一次 } |
3)css樣式
#errEdit { border: 1px solid #d9d9d9; height: 56px; width: 464px; color: rgba(0, 0, 0, 0.65); margin-right: 10px; } |
![](http://static.javashuo.com/static/loading.gif)
三、相關優化spa
1)去除先後 (將代碼中全部 替換成空格,而後trim())設計
.replace(/ */g," ").trim()
2)去除innerHtml中的標籤orm
.replace(/<[^>]+>/g,"")