javascript - 如何将插入符号放置在其中没有文本的 span 元素中?

标签 javascript html jquery contenteditable caret

关注 this SO post,我可以将插入符号放在span中元素,位于 div contenteditable="true" 内.
我可以定位任何 span我希望通过它的id ,同时还能够决定插入符号应该放在哪个字符之后。
但是我怎样才能把插入符号放在一个没有文本的范围内呢?
只需按原样使用该函数,就会出现以下错误:TypeError: Range.setStart: Argument 1 is not an object.此外,由于某种原因,当 span有内容,在 Firefox 中运行良好。但不是在 Chrome 中,插入符号位于 span 之外。 .有什么办法也可以解决这个问题?
如果它使事情变得更容易,我对 jQuery 持开放态度。
这是我的代码:
JSFiddle

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>

最佳答案

您可以考虑使用零宽度空间的一个很好的技巧(查看下面的代码)和 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()
}
span {
    font-weight: bold;
    background: yellow;
}
#editable:focus {
    white-space: pre;
}
<div contenteditable="true" id="editable">This should be <span></span> editable.</div>
<button onclick="placeCaretInSpan()">place caret</button>

关于javascript - 如何将插入符号放置在其中没有文本的 span 元素中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64370088/

相关文章:

javascript - 从 TinyMCE 编辑器隐藏文件编辑插入

java - 如何在java中使用selenium一次获取多个iframe内容

html - 如何使用 CSS 对齐标签,使其在所有浏览器中看起来都一样

javascript - 删除 html 类不会使用 jQuery removeClass 分离已删除的类功能

javascript - JavaScript 变量的范围在此脚本中如何工作?

javascript - jQuery图片懒加载还是优化web加载速度的解决方案吗

javascript - 何时使用自动函数执行

javascript - <ul> 标签图片列表向右浮动时超出边界

HTML 风格的独立悬停颜色

javascript - 用于从二进制流(字节数组)播放的视频播放器