Make selected text bold/unbold

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

    Why you are trying to bold text doing it by hand when you can use built in feature. Modern browsers implements execCommand function that allows to bold, underline etc. on text. You can write just:

    $('.embolden').click(function(){
        document.execCommand('bold');
    });
    

    and selected text will be made bold and if it's already bold, the text styling will be removed.

    A list of commands and a little doc can be found here. (More about browser support here).

    $(document).ready(function() {
      $('#jBold').click(function() {
        document.execCommand('bold');
      });
    });
    #fake_textarea {
      width: 100%;
      height: 200px;
      border: 1px solid red;
    }
    
    button {
      font-weigth: bold;
    }
    
    
    
    Select some text and click the button to make it bold...
    Or write your own text

提交回复
热议问题