【发布时间】:2020-10-15 10:58:12
【问题描述】:
在this SO 发布之后,我可以将插入符号放在span 元素内,该元素位于div contenteditable="true" 内。
我可以通过id 定位我想要的任何span,同时还可以决定插入符号应该放在哪个字符之后。
但是如何将插入符号放在没有文本的 span 中?
只需按原样使用该函数,就会得到这个错误:TypeError: Range.setStart: Argument 1 is not an object.
另外,由于某种原因,当 span 有内容时,它在 Firefox 中运行良好。但不是在 Chrome 中,插入符号位于 span 之外。有什么办法也可以解决这个问题?
我对 jQuery 持开放态度,如果它能让事情变得更容易的话。
这是我的代码:
function setCaret(x, y) {
var element = document.getElementById(x);
var range = document.createRange();
var node;
node = document.getElementById(y);
range.setStart(node.childNodes[0], 0);
var sel = window.getSelection();
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
element.focus();
}
body {
font-family: sans-serif;
}
input {
margin-bottom: 5px;
padding: 3px;
}
input:last-of-type {
margin-top: 30px;
}
div {
width: 300px;
padding: 5px;
border: solid 1px #000;
}
span {
font-weight: bold;
}
<input type="button" value="place caret" onclick="setCaret('editableDiv1', 'span1');">
<div id="editableDiv1" contenteditable="true" spellcheck="false">This one <span id="span1">is</span> working.</div>
<input type="button" value="place caret" onclick="setCaret('editableDiv2', 'span2');">
<div id="editableDiv2" contenteditable="true" spellcheck="false">This one <span id="span2"></span> is not.</div>
【问题讨论】:
-
在 Chrome 上,当我单击表示它正在工作并开始输入的那个上的“放置插入符号”按钮时,我输入的内容没有进入
span,它在 之前 跨度(例如,它不是粗体)。在 Firefox 上,我输入的内容在范围内。所以我不想这么说,但是即使span有内容,代码也已经有问题了。 -
火狐在这里。还没有在其他浏览器中测试过。在这里,它按预期工作。我单击该按钮,它将插入符号移动到跨度内,并在我键入时停留在那里。
-
您可以通过检查是否存在子节点并添加空文本元素来纠正第一个问题:
if (node.childNodes.length === 0) { var t = document.createTextNode(''); node.appendChild(t); }虽然无法解决 Chrome 问题 :-(
标签: javascript html jquery contenteditable caret