contentEditable - 如何强制在标签后面写入,而不是在里面

问题描述 投票:0回答:1

我有

div
contentEditable
,当我通过JS向其中添加元素时,例如:
<span>text</span>
之后我无法移动光标 - 所以当用户输入某些内容时,它会进入跨度。有什么办法可以预防吗?

<p class="line">Some text <span>text</span>[write_here]</p>

我想强制它写入

[write_here]
位置。

这是一个例子,当你添加元素并写入它时,它就会进入范围 - 红色。之后你就无法写出它了。

const input = document.querySelector('div.content');
const result = document.querySelector('div.result');
const addBtn = document.querySelector('button.addbtn');

input.addEventListener('input', () => {
  result.innerText = input.outerHTML;
});

const createElement = (content) => {
  const element = document.createElement('span');

  element.classList.add('mention');
  element.innerText = `@${content}`;

  return element;
};


addBtn.addEventListener('mousedown', () => {
  const element = createElement('test');
  
  const selection = window.getSelection();
  const selectedRange = selection.getRangeAt(0);
  
  selectedRange.deleteContents();
  selectedRange.insertNode(element);
  
  selectedRange.setStart(element, element.length);
  selectedRange.collapse(true);

  selection.removeAllRanges();
  selection.addRange(selectedRange);
  
  // How to properly move cursor after the `span` to write outside of the span. Even solve when user writes something and delete text right next to the end of the span. 
});
.content {
  width: 350px;
  height: 20px;
  background: lightblue;
}

span.mention {
  background: red;
}
<div class="content" contentEditable="true"><br/></div>
<button class="addbtn">Add element</button>
HTML:
<div class="result"></div>

javascript html selection contenteditable
1个回答
0
投票
function SetCursorAt(Node,Pos){

 var R=document.createRange(), S=window.getSelection();

 R.setStart(content.childNodes[Node],Pos); R.collapse(true);

 S.removeAllRanges(); S.addRange(R);

}

使用...

SetCursorAt(2,3);

注意: 假设您的编辑 ID 是“内容”。

© www.soinside.com 2019 - 2024. All rights reserved.