how to use jquery to insert a character at specified position into monospaced textarea

时间:2015-07-08 15:59:12

标签: javascript jquery html

I have a monospaced textarea (not unlike the stackexchange editor). When my user clicks, I need a character to automagically appear on the previous line using jQuery. I know I need to use .click() to bind a function to that event, but the logic of the function eludes me.

Desired Behavior...user will click at position of the asterisk *

Here is some text in my editor.
When I double click at a position*
I want to insert a new line above, with a new character at the same position

The above text should become the following after the function gets run

Here is some text in my editor.
                                 *
When I double click at a position*
I want to insert a new blank line above, at the same position

What I have tried:

I have found the caret jQuery plugin, which has a function called caret() that I can get to find the position of the the asterisk when I click (the position is 74).

<script src='jquery.caret.js'></script>

    $('textarea').click(function(e) {
      if (e.altKey){
        alert($("textarea").caret());
      }
    });

But I really need to know the position of the character within the line, not the entire textarea. So far this eludes me.

2 个答案:

答案 0 :(得分:3)

这里没有使用caret.js

$('textarea').dblclick(function(e){
    var text = this.value;
    var newLinePos = text.lastIndexOf('\n', this.selectionStart);
    var lineLength = this.selectionStart - newLinePos;
    var newString = '\n';
    for(var i=1; i < lineLength; ++i){
        newString += ' ';
    }
    newString += text.substr(this.selectionStart,this.selectionEnd-this.selectionStart);
    this.value = [text.slice(0, newLinePos), newString, text.slice(newLinePos)].join('');
});

Here's a fiddle.感谢this post将字符串插入指定位置的字符串&#39;。

刚才意识到在顶线上做这件事有点破,我回家后会看一眼!

<强>更新

修正了顶线问题。

if(newLinePos == -1){
    this.value = newString + '\n' + this.value;
} else {
    this.value = [text.slice(0, newLinePos), '\n'+newString, text.slice(newLinePos)].join('');
}

http://jsfiddle.net/daveSalomon/3dr8k539/4/

答案 1 :(得分:0)

假设您知道整个文本区域中插入符号的位置,您可以使用它。

function getCaretPosition(text, totalOffset) {
  var line = 0, pos = 0;
  for (var i = 0; i < Math.min(totalOffset, text.length); i++) {
    if (text[i] === '\n') {
      line++;
      pos = 0;
    } else {
      pos++;
    }
  }

  return { row: line, col: pos };
}

var caretPosition = getCaretPosititon($("textarea").val(), $("textarea").caret());