富文本编辑器的实现方法有两种
1.iframe+designMode
2.contenteditable
第一种 iframe+designMode
页面嵌入一个iframe标签,将属性designMode设为on
<iframe src="./嵌入本地的页面" name="iframe" style="width:400px;height:300px;" designMode='on'></iframe>
第二种 contenteditable
只需要给要编辑的标签设置 contenteditable=“true” 即可
<div contenteditable="true"></div>
编辑区域的一系列操作,比如加粗,斜体,居中之类的要用到的就是h5的execCommand
document.execCommand(命令的名称, 是否展示用户界面(一般为false), 某些命令的额外参数(如果不需要为null))
设置文本粗体 document.execCommand('bold', false, null);
实现原理:将选中内容取出来,放在b标签(如果是Safari和Chrome,会是b标签;如果是IE和Opera浏览器,会是strong标签;而Firefox则是span标签。浏览器不同,转化方式不同)里边,再放回去
设置斜体 document.execCommand('italic', false, null)
设置居中对齐 document.execCommand('fontsize', false, this.value);
设置字体大小 document.execCommand('fontsize', false, this.value);
撤销 document.execCommand('Undo')
回退 document.execCommand('Redo')
不过撤销回退仅限于文字的,,如果编辑块中手动插入标签是不起效的,可以用MutationObserver,后期的文章中会写到
富文本中的选取
window.getSelection 获取浏览器的选区
window.getSelection.getRangeAt(0) 获取浏览器的第一个选区range,谷歌只有一个选区,所以是0