我有一个等距的textarea(与stackexchange编辑器不同)。当用户单击时,我需要一个字符以使用jQuery自动出现在上一行中。我知道我需要使用.click()
将函数绑定(bind)到该事件,但是函数的逻辑使我难以理解。
所需的行为 ...用户将单击星号的位置*
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
函数运行后,上面的文本应变为以下内容
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
我尝试了什么:
我找到了caret jQuery plugin,它具有一个称为
caret()
的函数,单击该函数即可找到星号的位置(位置为74)。<script src='jquery.caret.js'></script>
$('textarea').click(function(e) {
if (e.altKey){
alert($("textarea").caret());
}
});
但是我真的需要知道字符在行中的位置,而不是整个文本区域。到目前为止,这使我难以理解。
最佳答案
这是一些没有使用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“将字符串插入指定位置的字符串”。
刚刚意识到,在最上面一行执行此操作有点麻烦,回到家时我会看看!
更新
修复了顶线问题。
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/
关于javascript - 如何使用jQuery将字符在指定位置插入等宽文本区域,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31297850/