![](/img/trans.png)
[英]Use JavaScript to place cursor at end of text in text input element
[英]Editable text inside span tags & place cursor at the end (Javascript)
我想要一个功能,单击“编辑”按钮将使跨标签内的文本内容可编辑。 我能够做到这一点,但无法弄清楚如何在文本末尾获得闪烁的 cursor。
下面是我的代码的简化版本。
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>
创建一个新range
addRange
使用getSelection
设置您希望将范围选择设置为 addRange 的节点...参见代码片段中的注释
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
https://developer.mozilla.org/en-US/docs/Web/API/Selection/removeAllRanges
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>
*这篇文章也可能对你有帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.