Make selected text bold/unbold

后端 未结 8 1942
谎友^
谎友^ 2020-12-08 12:18

I\'m wrapping the selected text in span tags, when you click a button. If I then select a different piece of text and click the button, that text also gets wrapped in tags.

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 13:00

    Copied function from this answer: Get parent element of a selected text

    Haven't really perfected this and I think this only works on exact selections but it gives you an idea of how to go around this. The click function checks if the parent element of the current selection has the class 'bold', if so it replaces that element with the original selection again.

    http://jsfiddle.net/XCb95/4/

    jQuery(function($) {
        $('.embolden').click(function(){
            var highlight = window.getSelection();  
            var span = '' + highlight + '';
            var text = $('.textEditor').html();
    
           var parent = getSelectionParentElement();
            if($(parent).hasClass('bold')) {
                  $('.textEditor').html(text.replace(span, highlight));
            } else {
                $('.textEditor').html(text.replace(highlight, span));
            }
    
        });
    });
    
    function getSelectionParentElement() {
        var parentEl = null, sel;
        if (window.getSelection) {
            sel = window.getSelection();
            if (sel.rangeCount) {
                parentEl = sel.getRangeAt(0).commonAncestorContainer;
                if (parentEl.nodeType != 1) {
                    parentEl = parentEl.parentNode;
                }
            }
        } else if ( (sel = document.selection) && sel.type != "Control") {
            parentEl = sel.createRange().parentElement();
        }
        return parentEl;
    }
    

提交回复
热议问题