- 需求背景:利用div的contentEditable="true",可编辑区域,插入一些标签包含文本,非纯文本格式, vue 项目中我是使用v-html渲染,v-model没法达到咱们的需求
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>可编辑的DIV(兼容IE8)</title>
<style type="text/css">
#content {
width: 500px;
height: 200px;
border: 1px solid #CCC;
}
</style>
</head>
<body>
<button id="insert" unselectable="on" onmousedown="return false">笑脸</button>
<div id="content" contenteditable="true"></div>
<script type="text/javascript">
// 在光标位置插入html代码,若是dom没有获取到焦点则追加到最后
window.onload= function(){
function insertAtCursor(jsDom, html) {
if (jsDom != document.activeElement) { // 若是dom没有获取到焦点,追加
jsDom.innerHTML = jsDom.innerHTML + html;
return;
}
var sel, range;
if (window.getSelection) {
// IE9 或 非IE浏览器
debugger
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(),
node, lastNode;
while ((node = el.firstChild)) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
// 点击插入
document.getElementById('insert').onclick = function() {
var html = ':)';
insertAtCursor(document.getElementById('content'), html);
};
}
</script>
</body>
</html>
demo效果

js api
- document.activeElement 该属性属于HTML5中的一部分,它返回当前得到焦点的元素,若是不存在则返回“body”。
- selection对象 selection是对当前激活选中区(即高亮文本)进行操做。 在非IE浏览器(Firefox、Safari、Chrome、Opera)下能够使用window.getSelection()得到selection对象,本文讲述的是标准的selection操做方法。文中绝大部份内容来自 https://developer.mozilla.org/en/DOM/Selection
方法
- getRangeAt(index) 从当前selection对象中得到一个range对象。
- addRange(range) 将range添加到selection当中,因此一个selection中能够有多个range。 注意Chrome不容许同时存在多个range,它的处理方式和Firefox有些不一样。
- removeRange(range) 从当前selection移除range对象,返回值undefined。 Chrome目前没有改函数,即使是在Firefox中若是用本身建立(document.createRange())的range做为参数也会报错。 若是用oSelction.getRangeAt()取到的,则不会报错。
- removeAllRanges() 移除selection中全部的range对象,执行后anchorNode、focusNode被设置为null,不存在任何被选中的内容。