阮一峰的IT笔记:首页 -> 分类 -> Javascript 查看所有文章:按分类 | 按月份

Javascript 获取页面上选中的文字(转)

在一些特殊应用中,我们需要获取页面上选中的文字,但是要实现这一需求,我们不得不面对那恼人的兼容问题,本文介绍了一个兼容性较好的解决方法。同时,也提供了一个在 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.

« Ati2dvag 蓝屏解决方法(转贴) | 首页 | 在线编辑器实现原理(兼容IE和FireFox)(转) »

About

This page contains a single entry from the blog posted on 2007年10月23日 17:36.

The previous post in this blog was Ati2dvag 蓝屏解决方法(转贴).

The next post in this blog is 在线编辑器实现原理(兼容IE和FireFox)(转).

Many more can be found on the main index page or by looking through the archives.

Powered by
Movable Type 3.33

Post a comment