简体   繁体   中英

Twitter Bootstrap button checkboxes toggling issue in making a wysiwyg text editor

I'd like to make a simple text editor to allow people to make the font bold, italicized or underlined. I'm a little confused on how to use the "active" class on twitter bootstrap's buttons to toggle functions such as adding different font styles to words in a textarea.

Here's my HTML:

<span class="btn-group" data-toggle="buttons-checkbox">
  <button class="btn btn-bold">Bold</button>
  <button class="btn btn-italics">Italics</button>
  <button class="btn btn-underline">Underline</button>
</span>    

<textarea></textarea>

here's my JS:

        $('.btn').click(function(){         
          if($('.btn-bold').hasClass('active')){                
            $('.btn-bold').toggle(
                 function() {
                     $('textarea').val($('textarea').val()+"<span style='font-weight:bold'>");}, 
                 function() {                     
                     $('textarea').val($('textarea').val()+"</span>");
            }); //toggle
          } //if
        });  //click  

I think i need to have code like this for each font-style: bold, italics, underline I toggle. But as you can see what I have for just making text bold is quite verbose (not to mention doesn't work) so there has to be a better way. Any thoughts would be greatly appreciated.

A better way to go about editing content would be to use the contentEditable attribute, since it has a great support across browsers and a great selection of commands ( execCommand ) one can execute to edit content out, more information here on the execCommand .

Here is a short demo i made about how to go about it:

Demo

Relevant code:

JS

var current;
$(function() {
    $("div[contenteditable]").focus(function() {
        current = this;
    });

    // bold
    $('.btn-bold').click(function() {
        document.execCommand('bold', false, null);
        $(current).contents().focus();
    });

    //italics
    $('.btn-italics').click(function() {
        document.execCommand('italic', false, null);
        $(current).contents().focus();
    });

    //underline
    $('.btn-underline').click(function() {
        document.execCommand('underline', false, null);
        $(current).contents().focus();
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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