【发布时间】:2014-01-20 19:34:32
【问题描述】:
使用 JS 或 jQuery 我想抓取光标前的整个单词。这意味着如果光标在某个单词之间,那么它会抓住它之前的整个单词。例如在字符串中:
This is a lame sentence.
如果我的光标在sentence 中的n 和t 之间,它将选择lame。如果我的光标在is 之间或之前,它将抓住This。
这是我尝试过的:
function getCaret(el) {
return el.selectionStart;
}
window.onload = function () {
var textarea = document.getElementById('content'),
status = document.getElementById('status');
textarea.onmouseup = textarea.onkeyup = function () {
status.innerHTML = getCaret(textarea);
var char = $('#content').val().split('');
var before = char.slice(0, getCaret(textarea));
words = before.join('').split(' ');
var word = words.pop()
wordBeforeCursor.innerHTML = word;
};
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<div id="status">Move the caret on the text:</div>
<textarea id = 'content'>
Here's a bunch of words
</textarea>
<div id="wordBeforeCursor"></div>
【问题讨论】:
标签: javascript jquery text-cursor