【问题标题】:Get selected text in a textbox获取文本框中选定的文本
【发布时间】:2010-03-04 08:45:46
【问题描述】:

如何在 HTML <input> 文本框元素中获取所选文本的字符位置? window.getSelection() 在文本框内不起作用。

【问题讨论】:

  • @Ant - 我们需要更多信息。您使用什么语言?仅在浏览器上(客户端)还是在服务器上?
  • 比如说,javascript 和 firefox。 window.getSelection() 在文本框内不起作用。

标签: javascript html input textbox


【解决方案1】:

如果您使用 jQuery,请查看 jQuery Caret 插件:jCaret

// Get start pos in intput box with id="box1"
$("#box1").caret().start

// Get end pos
$("#box1").caret().end

// Get selected text
$("#box1").caret().text

【讨论】:

    【解决方案2】:

    ........

    <script language=javascript>
    function getSelText()
    {
        var txt = '';
         if (window.getSelection)
        {
            txt = window.getSelection();
                 }
        else if (document.getSelection)
        {
            txt = document.getSelection();
                }
        else if (document.selection)
        {
            txt = document.selection.createRange().text;
                }
        else return;
    document.aform.selectedtext.value =  txt;
    }
    </script>
    
    <input type="button" value="Get selection" onmousedown="getSelText()"> 
    
    <form name=aform >
    <textarea name="selectedtext" rows="5" cols="20"></textarea>
    </form>
    

    参考:http://www.codetoad.com/javascript_get_selected_text.asp

    【讨论】:

      【解决方案3】:

      如果您不需要支持真正旧版本的 Internet Explorer,只需使用元素的 selectionEndselectionStart 属性即可。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2015-12-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-09-29
        • 1970-01-01
        相关资源
        最近更新 更多