Mik*_*els 6 html javascript jquery caret contenteditable
在这篇SO post 之后,我可以将插入符号放在一个span元素中,该元素位于div contenteditable="true".
我可以span通过它的来定位我想要的任何对象id,同时还可以决定插入符号应该放在哪个字符之后。
但是如何将插入符号放置在没有文本的跨度内?
只需按原样使用该函数,就会出现此错误: 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();
}Run Code Online (Sandbox Code Playgroud)
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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
您可以考虑使用零宽度空间(查看下面的代码)和 CSS 属性的一个很好的技巧,该属性white-space: pre允许在聚焦时空间“可见”。
function makeTextNode() {
return document.createTextNode('?') // <-- there a zero-width space between quotes
}
function placeCaretInSpan() {
const range = document.createRange()
const editable = document.getElementById("editable")
const span = editable.querySelector("span")
if (span.childNodes.length === 0) {
span.appendChild(makeTextNode()) // <-- you have to have something in span in order to place caret inside
}
range.setStart(span.childNodes[0], 1) // <-- offset by 1 to be inside SPAN element and not before it
let selection = window.getSelection()
range.collapse(true)
selection.removeAllRanges()
selection.addRange(range)
editable.focus()
}Run Code Online (Sandbox Code Playgroud)
span {
font-weight: bold;
background: yellow;
}
#editable:focus {
white-space: pre;
}Run Code Online (Sandbox Code Playgroud)
<div contenteditable="true" id="editable">This should be <span></span> editable.</div>
<button onclick="placeCaretInSpan()">place caret</button>Run Code Online (Sandbox Code Playgroud)