gpt4 book ai didi

javascript - 通过标签包围可编辑的元素;无法将光标移出新包围的选择

转载 作者:太空宇宙 更新时间:2023-11-04 00:58:38 25 4
gpt4 key购买 nike

我有一个 div,在我的学校元素网站上用作用户友好的文本编辑器。但是,如果我选择编辑器中的所有文本并尝试用 <code> tags </code> 包围它我无法将光标移出它,它不断将我键入的任何内容添加到同一个标签中,即 <code> .

一段时间后我放弃了,但后来我找到了this回答并尝试修改那里提到的 jsfiddle,希望它能正常工作。但运气不好。

比方说,如果我选择任何行中的最后一个单词并用 <code> 将其括起来标签,我可以在没有包围文本的地方将光标移出,但最后没有明文可以跳转,所以光标停留在 <code> 中。

如何确保光标不会卡在添加的标签中?也许是一种将光标移出它的方法?

jsFiddle

function surroundSelection() {
var code = document.createElement("code");
code.style.fontStyle = "italic";
code.style.color = "#333";
code.style.background = "#ddd";

if (window.getSelection) {
var sel = window.getSelection();
if (sel.rangeCount) {
var range = sel.getRangeAt(0).cloneRange();
range.surroundContents(code);
sel.removeAllRanges();
sel.addRange(range);
}
}
}
div, input {
padding:10px;

}

div {border:1px solid;}
<input type="button" onclick="surroundSelection()" value="Surround">
<div contenteditable="true">One two three four</div>

最佳答案

这里有一个稍微古怪的解决方法。不再使用环绕,而是将内容复制到新节点中。然后我们在末尾添加一个空格。现在可以在代码块后单击,即使所有文本都被选中也是如此。

编辑:添加 sel.collapseToEnd();根据评论(谢谢)。它通过将用户直接置于正常的打字上下文中来改善体验。但是,空间仍然是必需的,没有它就无法工作。

编辑:现在在开始和结束处添加空间。

编辑:删除间隔以发送到服务器。

function surroundSelection() {
let code = document.createElement("code");
code.style.fontStyle = "italic";
code.style.color = "#333";
code.style.background = "#ddd";
const newSpan = () => {
let span = document.createElement('span');
span.classList.add('codespacer');
span.innerHTML = '&nbsp;';
return span;
}

if (window.getSelection) {
let sel = window.getSelection();
if (sel.rangeCount) {
let range = sel.getRangeAt(0).cloneRange();
code.innerHTML = range.toString();
range.deleteContents();
range.insertNode(newSpan());
range.insertNode(code);
range.insertNode(newSpan());
sel.removeAllRanges();
sel.addRange(range);
sel.collapseToEnd();
}
}
}


function getContentForSave() {
let codeSection = document.querySelector('#codeSection');
// Copy into a temporary element (otherwise the text will change in the UI)
let tempSection = document.createElement('div');
tempSection.innerHTML = codeSection.innerHTML;
console.log(`Before: ${tempSection.innerHTML}`);

// Remove all codespacers
let spacers = tempSection.querySelectorAll('.codespacer');
for(let space of spacers) {
tempSection.removeChild(space);
}
console.log(`After: ${tempSection.innerHTML}`);

return tempSection.innerHTML;
}
div,
input {
padding: 10px;
}

div {
border: 1px solid;
}
<input type="button" onclick="surroundSelection()" value="Surround">
<div contenteditable="true" id="codeSection">One two three four</div>
<input type="button" onclick="getContentForSave();" value="Test For Save">

关于javascript - 通过标签包围可编辑的元素;无法将光标移出新包围的选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53981968/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com