</pre><p>1.关于cloneRange()和cloneContents()</p><p>cloneRange是创建一个新的range对象,表示与当前range对象相同的区域</p><p></p><pre code_snippet_id="1681934" snippet_file_name="blog_20160513_2_4163126" name="code" class="html"><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML5 编辑 API 之 Range 对象(二)</title>
</head>
<body>
<p id="p">这是用来克隆的文本</p>
<div id="div1"></div>
<button οnclick="cloneRange()">clone</button>
<div id="div2">
哈哈哈哈
</div>
<button οnclick="cloneContent()">clone</button>
<script>
function cloneRange() {
var rangeObj = document.createRange();
var p = document.getElementById("p");
rangeObj.selectNodeContents(p);
var rangeClone = rangeObj.cloneRange();
var div = document.getElementById("div1");
//alert(rangeClone.toString());
div.innerHTML = rangeClone;
}
function cloneContent(){
var div = document.getElementById("div2");
var rangeObj = document.createRange();
rangeObj.selectNodeContents(div);
var documentFragmengt = rangeObj.cloneContents();
div.appendChild(documentFragmengt);
}
</script>
</body>
</html>
cloneContents是把range内容复制到一个DocumentFragment中
extractContent:extractContents() 方法删除文档内容,并以 DocumentFragment 对象的形式返回它
例:
function moveContent(){
var div3 = document.getElementById("div3");
var div4 = document.getElementById("div4");
var rangeObj = document.createRange();
rangeObj.selectNodeContents(div3);
var del = rangeObj.extractContents();
div4.appendChild(del);
}
selection = document.getSelection;
selection.getRangeAt()
function insert(){
var btn = document.getElementById("btn");
var selection = document.getSelection();
if(selection.rangeCount>0){
var range = selection.getRangeAt(0);
range.insertNode(btn);
}
}