我正在尝试制作一个简单的文本编辑器,以便用户能够加粗/取消加粗选定的文本。我想使用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>
发布于 2020-08-12 04:21:43
这接近于您想要的,但将单词分组在一起,因此取消选择将从整个单词中删除。我不能完成这一点,因为我必须去,但应该是一个很好的起点。
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>
发布于 2020-08-12 02:33:06
var span = '';
jQuery(function($) {
$('.embolden').click(function(){
var highlight = window.getSelection();
if(highlight != ""){
span = '<span class="bold">' + highlight + '</span>';
}else{
highlight = span;
span = $('span.bold').html();
}
var text = $('.textEditor').html();
$('.textEditor').html(text.replace(highlight, span));
});
});您可以像这样定义一个函数,其中您的类的名称是"embolden“
https://stackoverflow.com/questions/63364212
复制相似问题