【问题标题】:Detecting if textarea content is selected using javascript检测是否使用javascript选择了textarea内容
【发布时间】:2011-09-13 08:26:08
【问题描述】:

我们有一些文本区域,其中包含一些用户可以复制到剪贴板的文本。

没有过多的细节,因为它只会使一个直截了当的问题复杂化:

是否可以检测 textareas 内容是否被“选中”?


我应该提到使用 onclick(或其他)事件处理程序(理想情况下...)不是一种选择。

因为此文本是由“文本区域之外”操作选择的。

流程有点如下:

选择下拉选项 -> 选择 textarea 中的文本

Textarea被点击(onclick) -> textarea中的文字被选中

我知道我们可以使用一大堆事件处理程序来检测 textarea 中文本的状态,但希望有一种更简单的方法,即通过 js 检测 textarea 中文本的状态。


谢谢

【问题讨论】:

标签: javascript html textarea


【解决方案1】:

selectionStartselectionEnd 属性保存选择索引。

var textarea = document.getElementById("textarea1");
if(textarea.selectionStart == textarea.selectionEnd) alert("Nothing is selected!")

【讨论】:

    【解决方案2】:

    此代码取自 this question,您需要稍微修改代码,但它显示了如何访问 Mozilla 和 IE 浏览器的选择 -

    function ShowSelection()
    {
      var textComponent = document.getElementById('Editor');
      var selectedText;
      // IE version
      if (document.selection != undefined)
      {
        textComponent.focus();
        var sel = document.selection.createRange();
        selectedText = sel.text;
      }
      // Mozilla version
      else if (textComponent.selectionStart != undefined)
      {
        var startPos = textComponent.selectionStart;
        var endPos = textComponent.selectionEnd;
        selectedText = textComponent.value.substring(startPos, endPos)
      }
      alert("You selected: " + selectedText);
    }
    

    【讨论】:

    • 选择这个答案是因为 trident 与正确的浏览器分支。谢谢!
    【解决方案3】:

    看看这个demo。他们使用jQuery - fieldSelection 插件。

    【讨论】:

    • 都是有效答案,但我们不使用 jquery :)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-25
    • 2013-08-31
    • 2010-11-27
    • 2019-07-31
    • 1970-01-01
    相关资源
    最近更新 更多