使用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;
width: 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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值