我尝试将div
文字插入contenteditable
并在添加div后选择div标记之间的文字:
div.innerHTML +='<div id="id">selecttext</div>'
但这不会选择selecttext
<html>
<head></head>
<body>
<div id="contenteditable" contenteditable></div>
<script>
var contenteditable = document.getElementById("contenteditable");
contenteditable.onkeyup = function (e) {
contenteditable.innerHTML += '<div>Start here</div>';
}
</script>
</body>
</html>
答案 0 :(得分:0)
您的问题分为三个部分:
- 将带有文字的
醇>div
插入contenteditable
:
contenteditable.innerHTML += '<div id="startHere">Start Here</div>';
- 查找startHere
醇>div
:
function findStartHereDiv(contenteditable) {
var childNodes = contenteditable.childNodes;
for(var i = 0; i < childNodes.length; i++) {
if(childNodes[i].id == 'startHere') {
return childNodes[i];
break;
}
}
return null;
}
- 选择startHere
醇>div
的文字:
function selectText(element) {
var doc = document
, text = doc.getElementById(element)
, range, selection
;
if (doc.body.createTextRange) {
range = document.body.createTextRange();
range.moveToElementText(text);
range.select();
} else if (window.getSelection) {
selection = window.getSelection();
range = document.createRange();
range.selectNodeContents(text);
selection.removeAllRanges();
selection.addRange(range);
}
}
这是你需要的吗?