使用H5的全局屬性contenteditable可以讓DOM元素及其子元素變的可編輯
<div contenteditable id="editor"> </div>
樣式代碼
html, body { overflow: hidden; width: 100%; height: 100%; }* { margin: 0; padding: 0; } #editor { width: 100%; height: 100%; outline: none; padding-left: 15px; }
* chrome 49下測試有效
以下方式使得用戶初始輸入的文本內容在p元素的包裹下
<div contenteditable id="editor" spellcheck="false"><p><br/></p></div>
默認規則如下


否則將直接作為#editor元素的文本節點,即<div contenteditable id="editor" spellcheck="false">文本內容</div>同事點擊Enter將新增div元素,即<div contenteditable id="editor" spellcheck="false">文本內容<div></div></div>
View Code
#editor中的所用元素都是可被刪除的,當#editor為空元素時,用戶再次輸出內容還會應用默認規則,這里要監聽這一狀態,發生時將<p><br/></p>添入其中,并且定位光標到p元素的最后
定位光標代碼
function cursorToEnd(element){ element.focus();var range = window.getSelection(); range.selectAllChildren(element); range.collapseToEnd(); }
window.getSelection() IE9已經支持
不定位可能發生以下情況
<div contenteditable id="editor" spellcheck="false"> 111111 <p><br/></p> </div>