使用iframe做为富文本编辑器

一、说明css

  在angular项目中,须要实现相似于富文本编辑器的将选中的文字高亮显示,并能够取消高亮,引入富文本编辑器(ckeditor或ueditor)均可实现,可是有点大材小用,因此考虑写一个输入框,一个标注按钮和一个取消标注的按钮实现该功能。html

二、实现设计模式

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;
}

 

三、相关优化spa

  1)去除先后&nbsp;(将代码中全部&nbsp;替换成空格,而后trim())设计

  .replace(/&nbsp;*/g," ").trim()

  2)去除innerHtml中的标签orm

  .replace(/<[^>]+>/g,"")
相关文章
相关标签/搜索