簡體   English   中英

Twitter Bootstrap按鈕復選框在制作所見即所得的文本編輯器時切換問題

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

我想制作一個簡單的文本編輯器,允許人們將字體粗體,斜體或下划線。 關於如何在twitter bootstrap的按鈕上使用“active”類來切換函數,例如在textarea中為單詞添加不同的字體樣式,我有點困惑。

這是我的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>

這是我的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  

我想我需要為每種字體樣式設置這樣的代碼:粗體,斜體,下划線切換。 但正如你所看到的那樣,僅僅使文本粗體化是非常冗長的(更不用說不起作用)所以必須有更好的方法。 任何想法將不勝感激。

編輯內容的更好方法是使用contentEditable屬性,因為它對瀏覽器有很好的支持,並且可以執行大量命令( execCommand )來編輯內容,更多信息請execCommand

這是一個關於如何進行的簡短演示:

演示

相關代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM