ectionStart之前和SelectionEnd之后获取所有

ectionStart之前和SelectionEnd之后获取所有

本文介绍了在SelectionStart之前和SelectionEnd之后获取所有文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在从头开始创建文本编辑器.

I am creating a text editor from scratch.

粗体代码

$('#bold').click(function(){

            var start = window.getSelection().toString();

            var bolded = '<b>' + start + '</b>';
            var cursorPositionBegin = $('#TextEditor').prop("selectionStart");
            var cursorPositionEnd = $('#TextEditor').prop("selectionEnd");
// to check
                alert(bolded);
            })

HTML代码

<table width="50%">
    <tr>
        <td>
            <div>
                <div>
                    <span><input type=button value="B" id="bold"></span>
                </div>
                <div contenteditable="true">
                    <textarea cols="47" rows="23" placeholder="editor" id="TextEditor"></textarea>
                </div>
            </div>
        </td>
    </tr>
</table>

当我为选定的一组字符单击#bold时,我想在#TextEditor中添加字符.我以为获得光标的开始和结束位置可能会有助于分解和将开始和结束与字符一起形成我需要的内容.

When I click #bold for a selected set of characters I want to add characters in the #TextEditor. I thought maybe getting the beginning and ending position of cursor could help break up and join the begin and end together along with the characters to form what I require.

我也使用jQuery

I also use jQuery

[更新1]还是有其他方法可以满足我的要求?[更新2]在放置#TextEditor ID的div中添加了contenteditable="true"

[update 1]Or is there an alternate method to do what I require?[update 2]added contenteditable="true" to div where #TextEditor id placed

您的帮助将不胜感激.

推荐答案

如@weBBer所述,您将不允许在textarea元素内添加标签,而应使用div并使用contentcontentable ="true"属性

As @weBBer said you will not allowed to add tag inside textarea element use div with attribute contenteditable="true" instead

$('#bold').click(function(){
  var string = window.getSelection().toString();
  var bolded = '<b>' + string + '</b>';
  var selC, range;
      if (window.getSelection) {
          selC = window.getSelection();
          if (selC.rangeCount) {
              range = selC.getRangeAt(0);
              range.deleteContents();
              range.insertNode(document.createTextNode(bolded));
          }
      } else if (document.selection && document.selection.createRange) {
          range = document.selection.createRange();
          range.text = bolded;
      }
}); 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table width="50%">
    <tr>
        <td>
            <div>
                <div>
                    <span><input type=button value="B" id="bold"></span>
                </div>
                <div contenteditable="true" style="height: 300px;width: 300px;border: 1px solid black">

                </div>
            </div>
        </td>
    </tr>
</table>

这篇关于在SelectionStart之前和SelectionEnd之后获取所有文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-31 03:27