在一些特殊应用中,我们需要获取页面上选中的文字,但是要实现这一需求,我们不得不面对那恼人的兼容问题,本文介绍了一个兼容性较好的解决方法。同时,也提供了一个在 FireFox 下获取 input 和 textarea 中选中文字的解决方案。
获取选中的普通页面上的文字,可以用下面的方法:
Javascript:
1.
2.
<script type="text/javascript">
3.
4.
// ˵Ã÷£º»ñÈ¡Ò³ÃæÉÏÑ¡ÖеÄÎÄ×Ö
5.
// ÕûÀí£ºhttp://www.CodeBit.cn
6.
7.
function getSelectedText() {
8.
if (window.getSelection) {
9.
// This technique is the most likely to be standardized.
10.
// getSelection() returns a Selection object, which we do not document.
11.
return window.getSelection().toString();
12.
}
13.
else if (document.getSelection) {
14.
// This is an older, simpler technique that returns a string
15.
return document.getSelection();
16.
}
17.
else if (document.selection) {
18.
// This is the IE-specific technique.
19.
// We do not document the IE selection property or TextRange objects.
20.
return document.selection.createRange().text;
21.
}
22.
}
23.
24.
</script>
25.
在 FireFox 下获取 input 或者 textarea 中选中的文字,可以用下面的方法:
Javascript:
1.
2.
<script type="text/javascript">
3.
4.
// ˵Ã÷£ºFireFox Ï»ñÈ¡ input »òÕß textarea ÖÐÑ¡ÖеÄÎÄ×Ö
5.
// ÕûÀí£ºhttp://www.codebit.cn
6.
7.
function getTextFieldSelection(e) {
8.
if (e.selectionStart != undefined && e.selectionEnd != undefined) {
9.
var start = e.selectionStart;
10.
var end = e.selectionEnd;
11.
return e.value.substring(start, end);
12.
}
13.
else return ""; // Not supported on this browser
14.
}
15.
16.
</script>
17.