Flex 如何获取Textarea的选择文本
效果:当选择Textarea中的文字时,获取到选择的文字。(有个很大的缺点,选择的时候必须从左往右划词,不能从右往左或者双击划词)
代码如下:
<?xml version="1.0" encoding="utf-8"?>
<!--
* ComingX.com Business License
*
* Copyright 2012. All rights reserved.
*
* @Author: ShanLanjie
* @Email: shanlanjie#gmail.com
* @Created date: 2012-3-23
-->
<s:WindowedApplication xmlns:fx="http://ns.adobe.com/mxml/2009"
xmlns:s="library://ns.adobe.com/flex/spark"
xmlns:mx="library://ns.adobe.com/flex/mx"
creationComplete="windowedapplication1_creationCompleteHandler(event)"
>
<fx:Script>
<![CDATA[
import mx.collections.ArrayCollection;
import mx.events.FlexEvent;
public var mouseDown:Boolean=false;
public var beginIndex:int; //记录开始选择的索引
public var endIndex:int; //记录选择结束的索引
public var chooseStr:String; //记录选择的词语
public var resultStr:String=""; //记录选择所剩结果
protected function windowedapplication1_creationCompleteHandler(event:FlexEvent):void
{
note.addEventListener(MouseEvent.MOUSE_DOWN,onMouseDownHandler);
}
/* 当鼠标按下时记录第一个字符索引值 */
public function onMouseDownHandler(evt:MouseEvent):void
{
mouseDown=true;
beginIndex=note.selectionBeginIndex;
this.note.addEventListener(MouseEvent.MOUSE_MOVE,onMoveHandler);
}
public function onMoveHandler(evt:MouseEvent):void
{
if(mouseDown)
{
this.note.addEventListener(MouseEvent.MOUSE_UP,onMouseUpHandler);
}
}
/* 记录选择完之后的索引值,并处理选择后的逻辑 */
public function onMouseUpHandler(evt:MouseEvent):void
{
endIndex=note.selectionEndIndex;
chooseStr=note.text.slice( beginIndex,endIndex ) //处理字符串,得到选中的词
trace(chooseStr);
}
]]>
</fx:Script>
<mx:TextArea width="800" height="50" id="note" fontSize="14" fontWeight="bold" editable="false" selectable="false" text="注意:选择词语的时候必须从左到右选择,不能双击选择或者从右往左选择"/>
</s:WindowedApplication>