繁体   English   中英

使用 Window.getSelection() 的粗体/非粗体选定文本

[英]Bold/unbold selected text using Window.getSelection()

我正在尝试制作一个简单的文本编辑器,以便用户能够加粗/取消粗体选定的文本。 我想使用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>

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

 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>

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));
    });
});

您可以像这样定义 function ,其中 class 的名称是“大胆的”

暂无
暂无

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

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