Javascript 获取文本框中选定的文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2377875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-22 23:59:47  来源:igfitidea点击:

Get selected text in a textbox

javascripthtmlinputtextbox

提问by Ant

How can I get the character positions of the selected text in an HTML <input>textbox element? window.getSelection()doesn't work inside textboxes.

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

回答by Ulf Lindback

If you're using jQuery, take a look at the jQuery Caret plugin: jCaret

如果您使用 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

回答by Sarfraz

........

…………

<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>

Reference: http://www.codetoad.com/javascript_get_selected_text.asp

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

回答by Ry-

In case you don't need to support really old versions of Internet Explorer, just use the element's selectionEndand selectionStartproperties.

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