Jun 29

在显示搜索结果,标记重点文本内容等很多时候都需要用到文本高亮显示,接下来的例子演示了Flex中如何利用TextRange类,高亮(hightlight)显示文本内容。下面的Demo中用了两个Slider,拖动来选择高亮文本范围。

让我们先来看一下Demo(可以右键View Source或点击这里察看源代码):


下面是完整代码(或点击这里察看):

Download: main.mxml
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" verticalAlign="middle" backgroundColor="white" viewSourceURL="srcview/index.html">
  3.  
  4.     <mx:Script>
  5.         <![CDATA[
  6.             import mx.events.SliderEvent;
  7.             import mx.controls.textClasses.TextRange;
  8.  
  9.             private var tr:TextRange;
  10.  
  11.             private function slider_change(evt:SliderEvent):void {
  12.                 updateTextRange();
  13.             }
  14.  
  15.             private function textArea_change(evt:Event):void {
  16.                 // Recalculate length.
  17.                 slider.maximum = textArea.length;
  18.  
  19.                 updateTextRange();
  20.             }
  21.  
  22.             private function updateTextRange():void {
  23.                 try {
  24.                     /* Default the TextArea control's text color back to black. */
  25.                     tr = new TextRange(textArea);
  26.                     tr.color = "black";
  27.                     tr.textDecoration = "normal";
  28.  
  29.                     /* Set the text color to red for the values in the Slider. */
  30.                     tr = new TextRange(textArea, false, slider.values[0], slider.values[1]);
  31.                     tr.color = colorPicker.selectedColor;
  32.                     tr.textDecoration = "underline";
  33.                 } catch (err:RangeError) {
  34.                     /* Somethin' ain't right! I dare say you have no text, son! */
  35.                 }
  36.             }
  37.         ]]>
  38.     </mx:Script>
  39.  
  40.     <mx:VBox width="380">
  41.         <mx:HBox>
  42.             <mx:Label text="Text selection color:" />
  43.             <mx:ColorPicker id="colorPicker" selectedColor="red" />
  44.         </mx:HBox>
  45.  
  46.         <mx:HBox>
  47.             <mx:Label text="Text selection range:" />
  48.             <mx:HSlider id="slider" thumbCount="2" liveDragging="true" snapInterval="1" dataTipPrecision="0" minimum="0" maximum="{textArea.length}" change="slider_change(event)" />
  49.             <mx:Label text="({slider.values.getItemAt(0)}, {slider.values.getItemAt(1)})" />
  50.         </mx:HBox>
  51.  
  52.         <mx:TextArea id="textArea" width="100%" height="120" change="textArea_change(event)">
  53.             <mx:text><![CDATA[The quick brown fox jumped over the lazy dog.]]></mx:text>
  54.         </mx:TextArea>
  55.     </mx:VBox>
  56.  
  57. </mx:Application>
代码:Peter deHaan 翻译/整理/编译:minidxer

written by Minidxer  |  tags: , , , , , ,

Related Post

Leave a Reply