htmlRange的使用

htmlRange的使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script> function rangeTest(){ var html; var showRangeDiv=document.getElementById("showRange"); var selection=document.getSelection(); if(selection.rangeCount>0){ html="您选取了<"+selection.rangeCount+"<内容<br/>" for(var i=0;i<selection.rangeCount;i++){ var range=selection.getRangeAt(i); html+="第"+(i+1)+"段内容为:"+range+"<br/>"; } showRangeDiv.innerHTML=html; } } </script>
</head>
<body>
    Selection对象和Range对象的使用
    <input type="button" value="点击我" onclick="rangeTest()">
    <div id="showRange"></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script> function deleteRangeContent(onlyContent) { var div = document.getElementById("div"); var rangobj = document.createRange(); if (onlyContent) { rangobj.selectNodeContents(div); rangobj.deleteContents(); } else { rangobj.selectNode(div); rangobj.deleteContents(); } } </script>
</head>
<body>
<div id="div" style="background-color: aqua;width: 300px;height: 50px">
    元素中内容
</div>
<button onclick="deleteRangeContent(true)">删除内容</button>
<button onclick="deleteRangeContent(false)">删除元素</button>

</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title></title>
    <script> function deleteChar(){ var div=document.getElementById("div"); var textNode=div.firstChild; var rangeObj=document.createRange(); rangeObj.setStart(textNode,1); rangeObj.setEnd(textNode,4); rangeObj.deleteContents(); } </script>
</head>
<body>
    <div id="div">
        要删除的文字
    </div>
    <button onclick="deleteChar()">删除文字</button>
</body>
</html>

你可能感兴趣的:(html,range)