跨度标签内的可编辑文本,并将光标置于末尾(JavaScript)

时间:2020-06-08 22:30:30

标签: javascript html

我想要一个功能,单击“编辑”按钮将使span标签内的文本内容可编辑。我能够做到这一点,但无法弄清楚如何在文本末尾显示闪烁的光标。

下面是我的代码的简化版本。

document.querySelector('button').addEventListener('click', function(){
  const span=document.querySelector('span');
  span.setAttribute('contentEditable', 'true');
  span.focus();
  let val=span.innerText;
  span.innerText='';
  span.innerText=val
})
<span>this is the span tag</span> <button>Edit</button>

1 个答案:

答案 0 :(得分:1)

创建一个新的range对象,将您希望使用addRange设置范围选择的节点设置为getSelection ...请参见代码片段中的注释

type hints

https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange

https://developer.mozilla.org/en-US/docs/Web/API/Window/getSelection

https://developer.mozilla.org/en-US/docs/Web/API/Range/selectNodeContents

document.querySelector('button').addEventListener('click', function() {
  const span = document.querySelector('span');
  span.setAttribute('contentEditable', 'true');
  span.focus();
  let val = span.innerHtml;
  span.innerHtml = '';
  span.innerHtml = val;
  
  //set a new range object
  let caret = document.createRange();
  //return the text selected or that will be appended to eventually
  let sel = window.getSelection();
  
  //get the node you wish to set range to
  caret.selectNodeContents(span);
  //set collapse to null or false to set at end of node
  caret.collapse(null);
  //make sure all ranges are removed from the selection object
  sel.removeAllRanges();
  //set all ranges to null and append it to the new range object
  sel.addRange(caret);
})
<span>this is the span tag</span> <button>Edit</button>

*这篇文章可能对您也有帮助...

https://developer.mozilla.org/en-US/docs/Web/API/Selection/removeAllRanges