简体   繁体   English

window.getselection()在FF和Chrome中不起作用

[英]window.getselection() not working in FF and chrome

I have texbox in my page and I am trying to get the length from the textbox. 我的页面中有texbox,我正在尝试从文本框中获取长度。 I know how to get the length in IE, but the following code is not working in FF and chrome. 我知道如何在IE中获取长度,但是以下代码在FF和chrome中不起作用。

<!DOCTYPE html>
<html>
<head>
<script>
function myFunction(obj)
{
alert("mouse up");
var r=window.getSelection().createRange();
alert(r.text.length);

}
</script>
</head>
<body>

<textarea id="myArea" cols="30" spellcheck="false" onmouseup=myFunction(this)>Select some text within this field.</textarea>


</body>
</html>

Textareas and text inputs have a different selection API from the main document selection. 文本区域和文本输入具有与主文档选择不同的选择API。 Use selectionStart and selectionEnd properties of the textarea/input. 使用文本区域/输入的selectionStartselectionEnd属性。

function myFunction(obj) {
    var selectedText = obj.value.slice(obj.selectionStart, obj.selectionEnd);
    alert(selectedText);
}

If you need support for IE <= 8, there is a different API again. 如果您需要IE <= 8的支持,请再次使用其他API。 See Caret position in textarea, in characters from the start 从头开始查看字符在文本区域中的插入位置

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM