我可以在文本表单输入中检索用户选择的文本吗?

Gab*_*iel 7 jquery

我试图只获取用户选择的输入字符串的选定部分.假设我有这样的输入:

<input type="text" name="first_name" id="first_name" value="Enter your name" />
Run Code Online (Sandbox Code Playgroud)

用户通过在文本字段中单击并拖动来选择"输入"单词.我可以用jQuery检索该文本吗?

我知道我可以通过这种方式获得全部价值:

$("#first_name").val();
Run Code Online (Sandbox Code Playgroud)

但到目前为止,我还是没有找到只选择"输入"的部分.任何人都能指出我正确的方向吗?谢谢!

编辑

我尝试了document.getSelection,它在Firefox上的静态文本元素(如"p")上运行良好.到目前为止,它对我的​​文本输入不起作用.

在IE中,window.selection.createRange().text在"p"和文本输入中都有效.

Gab*_*iel 1

好的,这是最终答案。当我们使用输入或文本区域时,看起来我们必须使用 SelectionStart 和 SelectionEnd 而不是 getSelection() 。这是我的测试代码:

$(".name").mouseup(function()
{
    var selected_text = "";
    if (window.getSelection) // Firefox
    {
        var text = $(this).val();
        selected_text = text.substring(document.activeElement.selectionStart, document.activeElement.selectionEnd);
    }
    else // IE
    {
        selected_text = document.selection.createRange().text;
    }
    alert(selected_text);
});
Run Code Online (Sandbox Code Playgroud)

我的 HTML 很简单:

<input type="text" name="name" class="name" value="Enter your name" />
Run Code Online (Sandbox Code Playgroud)

所以我终于明白了。感谢大家的意见!