简体   繁体   English

跨度标签内的可编辑文本并将 cursor 放在末尾(Javascript)

[英]Editable text inside span tags & place cursor at the end (Javascript)

I want a feature where clicking the Edit button will make the text content inside span tags editable.我想要一个功能,单击“编辑”按钮将使跨标签内的文本内容可编辑。 I was able to do that but couldn't figure out how to get the blinking cursor at the end of text.我能够做到这一点,但无法弄清楚如何在文本末尾获得闪烁的 cursor。

Below is the simplified version of my code.下面是我的代码的简化版本。

 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>

Create a new range object set the node you wish to set the range selection to addRange using getSelection ... See notes in code snippit创建一个新range addRange使用getSelection设置您希望将范围选择设置为 addRange 的节点...参见代码片段中的注释

https://developer.mozilla.org/en-US/docs/Web/API/Document/createRange 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/Window/getSelection

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

https://developer.mozilla.org/en-US/docs/Web/API/Selection/removeAllRanges 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>

*This post may also be helpful to you... *这篇文章也可能对你有帮助...

How to set caret(cursor) position in contenteditable element (div)? 如何在 contenteditable 元素(div)中设置插入符号(光标)position?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM