Make selected text bold/unbold

后端 未结 8 1922
谎友^
谎友^ 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:12

    This code goes thru the content of the textEditor and removes all the span tags. It should do the trick.

    jQuery(function($) {
        $('.embolden').click(function(){
            $('.textEditor span').contents().unwrap();
            var highlight = window.getSelection();  
            var span = '<span class="bold">' + highlight + '</span>';
            var text = $('.textEditor').html();
            $('.textEditor').html(text.replace(highlight, span));
        });
    });
    
    0 讨论(0)
  • 2020-12-08 13:14

    Modern browsers utilize the execCommand function that allows you to embolden text very easily. It also provides other styles like underline etc.

    <a href="#" onclick="emboldenFont()">Bold</a>
    
    function emboldenFont() {
        document.execCommand('bold', false, null);
    }
    
    0 讨论(0)
提交回复
热议问题