【问题标题】:Get selected / highlighted text with code mirror from text area not working从文本区域获取带有代码镜像的选定/突出显示文本不起作用
【发布时间】:2016-01-09 10:08:27
【问题描述】:

在带有codemirror 的文本区域上,我试图能够选择/突出显示文本,然后能够单击我的粗体按钮并应将粗体标签包裹在其周围。

我看过

SO Question 1 , SO Question 2

但似乎不适用于代码镜像。

我的问题是:对于codemirror,我怎样才能抓住选定的文本,然后确保当我点击粗体按钮时它正确地换行了文本?

Codepen Code View

Codepen Full View

脚本

var editor = document.getElementById('text-editor');
var string = grabed_text();

    $("#text-editor").each(function (i) {
        editor = CodeMirror.fromTextArea(this, {
            lineNumbers: true,
            mode: 'html'
        });

        $('button').click(function(){

          var val = $(this).data('val');


          switch(val){
            case 'bold': editor.replaceSelection('<b>' + string + '</b>');
            break;
           }
        });
    });

function grabed_text() {

}    

HTML

<div class="container">

<div class="row">

<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div class="panel panel-default"  onLoad="text_editor();">
<div class="panel-heading">
<button type="button" data-val="bold" class="btn btn-default">Bold</button>
</div>
<div class="panel-body">
<textarea id="text-editor" name="text-editor" class="form-control"></textarea>
</div>
</div>
</div>

</div>

<div class="row">

<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12">
<div id="question-iframe"></div>
</div>

</div>

</div>

【问题讨论】:

    标签: javascript jquery codemirror


    【解决方案1】:

    您的代码中的问题在于您处理粗体按钮的开关盒。

     case 'bold': 
          editor.replaceSelection('<b>' + string + '</b>');
          break;
    

    在这里,您通过将 &lt;b&gt; 标签包裹在 string 变量周围来替换当前选择,但它没有在任何地方定义。理想情况下,它应该反映编辑器的当前选择。所以我建议你改变你的代码如下。

      // inside your click handler
      var val = $(this).data('val');
      var string = editor.getSelection();
    
      switch(val){
         case 'bold': { 
                   editor.replaceSelection('<b>' + string + '</b>');
                break;
              }
      }
    

    这是一个 Pen 进行了上述更改。

    【讨论】:

    • 感谢您的帮助
    猜你喜欢
    • 2011-07-19
    • 2010-09-13
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多