1、說明
在angular項目中,需要實現類似於富文本編輯器的將選中的文字高亮顯示,並可以取消高亮,引入富文本編輯器(ckeditor或ueditor)都可實現,但是有點大材小用,所以考慮寫一個輸入框,一個標注按鈕和一個取消標注的按鈕實現該功能。

2、實現
1)在html中添加iframe
| <iframe id='errEdit' (mouseout)="leaveIframe()"></iframe> 注:其中的mouseout事件是為了監測內容輸入(blur事件不起作用)。 |
2)在ts中初始化並實現相關操作
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; } |

3、相關優化
1)去除前后 (將代碼中所有 替換成空格,然后trim())
.replace(/ */g," ").trim()
2)去除innerHtml中的標簽
.replace(/<[^>]+>/g,"")