我正在尝试从textarea获取当前单词,现在单击我的光标 [英] I am trying to get current word from textarea,where my cursor is clicked now
本文介绍了我正在尝试从textarea获取当前单词,现在单击我的光标的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在这里,我通过使用以下代码选择单词,例如单击我需要获取"
Here I get the word by selected using the following code,like by clicking i need to get
$('#select').click(function (e) {
textAreaValue = $("#para")[0],
startValue = textAreaValue.selectionStart,
endValue = textAreaValue.selectionEnd,
oldText = textAreaValue.value;
text = oldText.substring(startValue, endValue);
alert(text);
}
//我使用此代码来获取光标所在位置的当前单词
// I use this code to get current word where my cursor is placed
$('#textarea').click(function(){
$('#textarea').click(function() {
textAreaValue = $("#para")[0];
startValue = textAreaValue.selectionStart;
endValue = textAreaValue.selectionEnd;
oldText = textAreaValue.value;
startPosition = startValue;
textlength = (textAreaValue.value).length;
while(startPosition >= 0 ){
if(oldText.substring(startPosition-1, startPosition) == ' '){
break;
}
startPosition--;
}
endPosition = endValue;
while(true){
var eval = oldText.substring(endPosition, endPosition+1);
if(eval == ' ' || eval == '\n' || eval == '\r' || eval == '\t'|| endPosition == textlength){
break;
}
endPosition++;
}
text = oldText.substring(startPosition, endPosition);
textAreaValue.selectionStart = startPosition;
textAreaValue.selectionEnd = endPosition;
alert(text);
return false;
});
推荐答案
如果用户突出显示文本,则可以获取所选文本:
If the user highlights text, you can get the selected text:
$('textarea').on('click', function() {
var text = $(this).html();
var start = $(this)[0].selectionStart;
var end = $(this)[0].selectionEnd;
var text = text.substr(start, end - start);
alert(text);
});
如果用户只是单击文本区域,则可以得到光标所在的单词:
If the user just clicks in the textarea, you can get the word the cursor is on:
var stopCharacters = [' ', '\n', '\r', '\t']
$('textarea').on('click', function() {
var text = $(this).html();
var start = $(this)[0].selectionStart;
var end = $(this)[0].selectionEnd;
while (start > 0) {
if (stopCharacters.indexOf(text[start]) == -1) {
--start;
} else {
break;
}
};
++start;
while (end < text.length) {
if (stopCharacters.indexOf(text[end]) == -1) {
++end;
} else {
break;
}
}
var currentWord = text.substr(start, end - start);
alert(currentWord);
});
这篇关于我正在尝试从textarea获取当前单词,现在单击我的光标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文