jquery 我正在尝试从文本区域获取当前单词,现在我的光标被单击了

t1qtbnec  于 2022-12-29  发布在  jQuery
关注(0)|答案(3)|浏览(99)

在这里,我使用下面的代码通过selected获取单词,就像单击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);
}

//我用这段代码从光标所在的位置获取当前单词
$('#文本区域').单击(函数(){

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;

});
e0bqpujr

e0bqpujr1#

如果用户高亮显示文本,则可以获得选定的文本:

$('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);
});

jsfiddle
如果用户只是在文本区域中单击,则可以获得光标所在的单词:

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);
});

jsfiddle

qvsjd97n

qvsjd97n2#

jQuery textRange插件可以完成这一任务,甚至更多。

6xfqseft

6xfqseft3#

您可以使用浏览器的选择API轻松完成此操作:

const selection = window.getSelection();

// Move cursor to the end of the word
selection?.modify('move', 'forward', 'word');

// Extend selection to the start of the word
selection?.modify('extend', 'backward', 'word');

// Get the selected text
const text = selection.toString();

// You can collapse selection later if you like
selection.collapse();

相关问题