contenteditable:控制元素可以像富文本编辑器一样编辑
<div contenteditable="true">
This text can be edited by the user.
</div>
当一个HTML元素的contenteditable属性被设置为true时,"document.execCommand()”方法便可使用。通过该方法,你可以运行相关commands 来操作可编辑区域的内容。
需要注意一点,不同的浏览器对换行有不同的处理,但是我们可以指定默认的换行行为(Firefox 插入<br>、IE/Opera将使用<p>、 Chrome/Safari 将使用 <div>):document.execCommand("defaultParagraphSeparator", false, "p");
一般使用contenteditable还会使用下面三个方法:
document.createTextNode、document.createRange、window.getSelection
document.createTextNode
创建一个纯文本节点document.createTextNode(data: string),继承于Node接口。
document.createRange
创建一个Range(接口表示一个包含节点与文本节点的一部分的文档片段),其中Range.getBoundingClientRect()/Element.getBoundingClientRect() 这个方法是新加的比较有用的方法(用于获得页面中某个元素的左,上,右和下分别相对浏览器视窗的位置)。