首页 > 其他 > 详细

H5富文本编辑器之初始化用于编辑的DOM-遁地龙卷风

时间:2017-07-06 21:41:40      阅读:316      评论:0      收藏:0      [点我收藏+]

使用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;
}
View Code

 

* 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();
    
}
View Code

window.getSelection() IE9已经支持

不定位可能发生以下情况

技术分享
<div  contenteditable id="editor" spellcheck="false">
    111111
    <p><br/></p>
</div>
View Code

 

H5富文本编辑器之初始化用于编辑的DOM-遁地龙卷风

原文:http://www.cnblogs.com/resolvent/p/7128411.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!