【问题标题】:How to get selected text from a textbox control with JavaScript如何使用javascript从文本框控件中获取选定的文本
【发布时间】:2010-09-21 12:06:29
【问题描述】:

我有一个文本框和一个链接按钮。 当我写一些文本,然后选择其中一些然后单击链接按钮时,从文本框中选择的文本必须与消息框一起显示。

我该怎么做?


当我点击下方文本框的提交按钮时,消息框必须显示 Lorem ipsum。因为在区域中选择了“Lorem ipsum”。


如果我从页面中选择任何文本并单击它正在工作的提交按钮,但如果我将文本写入文本框并制作它,它不是。因为当我点击另一个空间时,文本框的选择被取消。

现在的问题是,当我从文本框中选择一个文本并单击任何其他控件或空间时,必须仍然选择被选择的文本。

它是怎么做的?

【问题讨论】:

标签: javascript html textarea textselection selectedtext


【解决方案1】:

好的,这是我的代码:

function ShowSelection()
{
  var textComponent = document.getElementById('Editor');
  var selectedText;

  if (textComponent.selectionStart !== undefined)
  {// Standards Compliant Version
    var startPos = textComponent.selectionStart;
    var endPos = textComponent.selectionEnd;
    selectedText = textComponent.value.substring(startPos, endPos);
  }
  else if (document.selection !== undefined)
  {// IE Version
    textComponent.focus();
    var sel = document.selection.createRange();
    selectedText = sel.text;
  }

  alert("You selected: " + selectedText);
}

问题,虽然我为 IE 提供的代码在很多网站上都有提供,但我无法让它在我当前系统上的 IE6 副本上运行。也许它对你有用,这就是我给它的原因。
您寻找的技巧可能是 .focus() 调用,将焦点返回给 textarea,以便重新激活选择。

[UPDATE] 我通过 onKeyDown 事件得到了正确的结果(选择内容):

document.onkeydown = function (e) { ShowSelection(); }

所以代码是正确的。同样,问题是通过单击按钮获得选择...我继续搜索。

[更新] 使用li 标记绘制的按钮没有成功,因为当我们单击它时,IE 会取消选择之前的选择。上面的代码可以使用一个简单的input 按钮,不过...

【讨论】:

  • 8 年前的帖子,我知道。但无论如何......也许你可以尝试:在你的按钮上单击调用 $('').focus(),然后调用 ShowSelection() 从活动元素中获取部分?
  • 这可以做到a lot more simply
【解决方案2】:

这是一个更简单的解决方案,基于鼠标上移时发生文本选择的事实,因此我们为此添加了一个事件侦听器:

document.querySelector('textarea').addEventListener('mouseup', function () {
  window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd)
  // window.getSelection().toString();
});
<textarea>
  Select some text
</textarea>
<a href="#" onclick=alert(mySelection);>Click here to display the selected text</a>

这适用于所有浏览器。

如果您还想通过键盘处理选择,请使用相同的代码为 keyup 添加另一个事件侦听器。

如果不是这个Firefox bug filed back in 2001(是的,14 年前),我们可以将分配给window.mySelection 的值替换为window.getSelection().toString(),它适用于IE9+ 和所有现代浏览器,并且还可以选择在 DOM 的非文本区域部分制作。

【讨论】:

  • 所以你批评七年前给出的解决方案,但没有表明你不会在 IE developer.mozilla.org/en-US/docs/Web/API/Window/getSelection
  • @PhiLho:令人难以置信的是,它在 FF 中不起作用——这个错误是 14 年前提交的。更新了答案。
  • 此解决方案运行良好,但是如果光标超出文本区域“框”,则不会触发该事件。您必须添加以下代码才能使其在这种情况下工作: document.querySelector('textarea').addEventListener('mouseleave', function () { window.mySelection = this.value.substring(this.selectionStart, this.selectionEnd ); });当您离开 textarea 时,该事件也会触发,因此保留您的选择。
【解决方案3】:

function disp() {
  var text = document.getElementById("text");
  var t = text.value.substr(text.selectionStart, text.selectionEnd - text.selectionStart);
  alert(t);
}
<TEXTAREA id="text">Hello, How are You?</TEXTAREA><BR>
<INPUT type="button" onclick="disp()" value="Select text and click here" />

【讨论】:

  • 这恰好可以工作,但是如果您在disp() 中有更复杂的代码,那么当该代码从文本区域获得选择时(例如构造一个selection-menu,浏览器可能已经清除了它因为按钮上发生的click 事件意味着textarea 接收到blur 事件,这会清除选择。My answer 通过在发生选择时将选择保存在变量中来解决这个问题。
【解决方案4】:

对于 Opera、Firefox 和 Safari,您可以使用以下函数:

function getTextFieldSelection(textField) {
    return textField.value.substring(textField.selectionStart, textField.selectionEnd);
}

然后,您只需将对文本字段元素(如文本区域或输入元素)的引用传递给函数:

alert(getTextFieldSelection(document.getElementsByTagName("textarea")[0]));

或者,如果您希望

HTMLTextAreaElement.prototype.getSelection = HTMLInputElement.prototype.getSelection = function() {
    var ss = this.selectionStart;
    var se = this.selectionEnd;
    if (typeof ss === "number" && typeof se === "number") {
        return this.value.substring(this.selectionStart, this.selectionEnd);
    }
    return "";
};

那么,你只需:

alert(document.getElementsByTagName("textarea")[0].getSelection());
alert(document.getElementsByTagName("input")[0].getSelection());

例如。

【讨论】:

    【解决方案5】:

    jQuery-textrange的忠实粉丝

    下面是一个非常小的、独立的示例。下载 jquery-textrange.js 并复制到同一个文件夹。

    <!doctype html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>jquery-textrange</title>
    <script src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script src="jquery-textrange.js"></script>
    
    <script>
    /* run on document load **/
    $(document).ready(function() {
        /* run on any change of 'textarea' **/
        $('#textareaId').bind('updateInfo keyup mousedown mousemove mouseup', function() {
            /* The magic is on this line **/
            var range = $(this).textrange();
            /* Stuff into selectedId.  I wanted to store this is a input field so it can be submitted in a form. **/
            $('#selectedId').val(range.text);
        });
    });
    </script>
    </head>
    <body>
    
        The smallest example possible using 
        <a href="https://github.com/dwieeb/jquery-textrange">
           jquery-textrange
        </a><br/>
        <textarea id="textareaId" >Some random content.</textarea><br/>
        <input type="text"  id="selectedId"  ></input>
    
    </body>
    </html>
    

    【讨论】:

    • 不需要任何 jQuery 插件。见my answer
    【解决方案6】:
    //Jquery
    var textarea = $('#post-content'); 
    var selectionStart = textarea.prop('selectionStart');
    var selectionEnd = textarea.prop('selectionEnd');
    var selection = (textarea.val()).substring(selectionStart,selectionEnd);
    
    //Javascript
    var textarea = document.getElementById("post-content");   
    var selection = (textarea.value).substring(textarea.selectionStart,textarea.selectionEnd);
    

    【讨论】:

      猜你喜欢
      • 2012-11-11
      • 2011-03-11
      • 2010-12-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多