繁体   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