使用iframe作为富文本编辑器

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;
464px;
color: rgba(0, 0, 0, 0.65);
margin-right: 10px;
}

3、相关优化

  1)去除前后&nbsp;(将代码中所有&nbsp;替换成空格,然后trim())

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

  2)去除innerHtml中的标签

  .replace(/<[^>]+>/g,"")
  

 

原文地址:https://www.cnblogs.com/boreguo/p/10266960.html