在div
标记(id = mainDiv)中插入新文本时遇到一些问题。我想在插入当前插入位置的文本时将其添加,然后将光标移动到新位置(旧位置+ text.length)。但我看错了逻辑。请帮帮我!
function getCharacterOffsetWithin(range, node)
{
var treeWalker = document.createTreeWalker(
node,
NodeFilter.SHOW_TEXT,
function(node) {
var nodeRange = document.createRange();
nodeRange.selectNodeContents(node);
return nodeRange.compareBoundaryPoints(Range.END_TO_END, range) < 1 ?
NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT;
},
false
);
var charCount = 0;
while (treeWalker.nextNode()) {
charCount += treeWalker.currentNode.length;
}
if (range.startContainer.nodeType == 3) {
charCount += range.startOffset;
}
return charCount;
}
function input(text)
{
//FIX LOGIC!
var target;
if(window.getSelection)
{
target =window.getSelection().getRangeAt(0).commonAncestorContainer;
target = ((target.nodeType===1)?target:target.parentNode);
}
else if(document.selection) {
target = document.selection.createRange().parentElement();
}
var sel = window.getSelection();
var range = sel.getRangeAt(0);
var newpos = getCharacterOffsetWithin(range, target) + text.length;
range.deleteContents();
range.insertNode(document.createTextNode(text));
target.focus();
var newRange = document.createRange();
newRange.setStart(target, newpos);
newRange.setEnd(target, newpos);
newRange.collapse(false);
sel.removeAllRanges();
sel.addRange(newRange);
}
&#13;
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script src="formulas.js"></script>
<link rel="stylesheet" href="styles.css" type="text/css" media="screen" />
</head>
<body id="main" spellcheck="false">
<span contenteditable="false">
<button onclick="input('Ln')">Ln</button>
<button onclick="input('Lg')">Lg</button>
<button onclick="input('±');">+-</button>
<button onclick="input('x²')">x²</button>
<button onclick="input('α')">α</button>
<button onclick="input('β')">β</button>
<button onclick="input('γ')">γ</button>
<button onclick="input('Σ')">Σ</button>
<button onclick="input('÷')">÷</button>
<button onclick="input('×')">×</button>
</span>
</p>
<div id = "mainDiv"contenteditable="true" onclick="mainClick(event)">dwawdawdd</div>
<div class="big" onclick="setCursorPositionToEnd();"></div>
</body>
</html>
&#13;
答案 0 :(得分:0)
我找到了答案。
var textNode = document.createTextNode(text);
range.insertNode(textNode);
target.focus();
var newRange = document.createRange();
newRange.setStart(textNode, text.length);
我只是为新节点设置了起始位置。