window.getselection()在FF和chrome中不起作用 [英] window.getselection() not working in FF and chrome
本文介绍了window.getselection()在FF和chrome中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的网页中有texbox,我试图从文本框中获取长度。我知道如何在IE中获取长度,但以下代码在FF和chrome中不起作用。
I have texbox in my page and I am trying to get the length from the textbox. I know how to get the length in IE, but the following code is not working in FF and 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>
推荐答案
文本和文本输入有不同的选择API主要文件选择。使用textarea / input的 selectionStart
和 selectionEnd
属性。
Textareas and text inputs have a different selection API from the main document selection. Use selectionStart
and selectionEnd
properties of the textarea/input.
function myFunction(obj) {
var selectedText = obj.value.slice(obj.selectionStart, obj.selectionEnd);
alert(selectedText);
}
如果您需要IE< = 8的支持,则有一个不同的API再次。请参阅文本中的插入位置,以开头字符开头
If you need support for IE <= 8, there is a different API again. See Caret position in textarea, in characters from the start
这篇关于window.getselection()在FF和chrome中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文