【问题标题】:How do I select the whole word before the cursor?如何选择光标前的整个单词?
【发布时间】:2014-01-20 19:34:32
【问题描述】:

使用 JS 或 jQuery 我想抓取光标前的整个单词。这意味着如果光标在某个单词之间,那么它会抓住它之前的整个单词。例如在字符串中:

This is a lame sentence.

如果我的光标在sentence 中的nt 之间,它将选择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>

FIDDLE

【问题讨论】:

    标签: javascript jquery text-cursor


    【解决方案1】:

    在您的代码中添加这些行,

    last=words.length-1;
    wordBeforeCursor.innerHTML = words[last] ? words[last] :'';
    

    var word = words.pop();之后

    Demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-15
      • 2012-12-23
      • 1970-01-01
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2016-05-08
      相关资源
      最近更新 更多