gpt4 book ai didi

javascript - 使用 Window.getSelection() 加粗/取消加粗所选文本

转载 作者:行者123 更新时间:2023-12-02 19:18:32 28 4
gpt4 key购买 nike

我正在尝试制作一个简单的文本编辑器,以便用户能够加粗/取消加粗所选文本。我想使用 Window.getSelection() 而不是 Document.execCommand()。它完全符合我的要求,但是当您将任何文本加粗时,就无法取消加粗。我希望它能够加粗和取消加粗任何选定的文本。我尝试了几件事但没有成功。

function addBold(){
const selection = window.getSelection().getRangeAt(0);
const selectedText = selection.extractContents();
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selectedText);
selection.insertNode(span);
};
.bold-span {font-weight: bold;}
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>

最佳答案

这与您想要的很接近,但是将单词组合在一起,因此取消选择将从整个单词中删除。由于我必须离开,因此无法完成此操作,但这应该是一个很好的起点。

function addBold(){
const selection = window.getSelection().getRangeAt(0);

let selectedParent = selection.commonAncestorContainer.parentElement;

//console.log(parent.classList.contains("bold-span"))
//console.log(parent)
let mainParent = selectedParent;
if(selectedParent.classList.contains("bold-span"))
{
var text = document.createTextNode(selectedParent.textContent);
mainParent = selectedParent.parentElement;
mainParent.insertBefore(text, selectedParent);
mainParent.removeChild(selectedParent);
mainParent.normalize();
}
else
{
const span = document.createElement("span");
span.classList.toggle("bold-span");
span.appendChild(selection.extractContents());
//selection.surroundContents(span);
selection.insertNode(span);
mainParent.normalize();
}

//selection is set to body after clicking button for some reason
//https://stackoverflow.com/questions/3169786/clear-text-selection-with-javascript
if (window.getSelection) {
if (window.getSelection().empty) { // Chrome
window.getSelection().empty();
} else if (window.getSelection().removeAllRanges) { // Firefox
window.getSelection().removeAllRanges();
}
} else if (document.selection) { // IE?
document.selection.empty();
}

};
.bold-span {font-weight: bold;}
<p contentEditable>Bold anything here and unbold it</p>
<button onclick="addBold()">Bold</button>

关于javascript - 使用 Window.getSelection() 加粗/取消加粗所选文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63364212/

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