金山词霸即划即译设计随笔(三)

如何获取光标的位置,在上一节中已经解决了。现在我们来进行第二步,如何获取选定的文本。

这一点也是至关重要的,因为我们要把用户选择的文本作为用户提交的输入来处理,作为参数提交查询请求。

原来从来没尝试过这一点,只好求助于google了,虽然第一次查相关资料有些盲目,但很幸运的是,我还是找到了。

var  text = document.selection.createRange().text;

上面这句看起来很简单,就是为了得到用户在浏览器窗口中选择的文本对象,然后存入变量text中,以备下面使用。

为了便于大家理解,特在MSDN上抓来了下面的一段有关selection对象的说明,仅供参考:

Remarks

You can use the selection object as input from the user to identify which portion of the document to act on, or as output to the user to show the results of an action.

Users and scripts can create selections. Users create selections by dragging the mouse over a portion of the document. Scripts create selections by calling the select method on a text range or similar object. To get the active selection, apply the selection keyword to the document object. To carry out work on a selection, create a text range object from the selection using the createRange method.

A document can have only one selection at a time. The selection has a type that determines whether it is empty or contains a block of text or elements. Although an empty selection contains nothing, you can use it to mark a position in the document.

简单翻译如下:

说明:你可以利用selection对象把用户在当前窗口中的具体操作位置当作用户输入,也可以把它作为响应用户某一操作的结果输出给用户。

用户和编码人员可以创建selection对象。用户可以通过在窗体中的某个位置上拖动鼠标来创建selection对象,而编码人员则可以对文本序列或简单的对象调用select()方法来创建它。获取当前的选择内容,可以应用在文档内选择的关键字。为了实现选择内容的获取,可以使用selection对象的createRange()方法来创建一个文本序列。

一个文档对象往往只能有一个selection对象。selection对象拥有可以判断它是否为空或是否包含文本块或其他元素的特性。尽管一个空的selection对象不包含任何内容,但你可以用它来标记文档的一个位置。MSDN参考地址

在把从selection对象获得的值赋给text变量后,你就可以通过.length属性获取并判断它的长度了,以决定它是否为空。

MSN跟我交流

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值