2012-11-05 116 views
3

我有一个关于as3的文本框占位符的快速问题。as3文本框占位符

所有现代浏览器或移动应用都支持文本输入字段的占位符。一旦你点击它,焦点就会移动到文本的开头,并且占位符会一直保留,直到你开始输入。

想知道这是否可以在as3上实现吗?

干杯 比尔

+0

你可以模仿Flex框架的实现[的TextInput提示文本]的(http://help.adobe.com/en_US/flex/using/WS19f279b149e7481ccb9899c12d861ca08a-8000.html)。 –

+0

谢谢杰森,但是当焦点文字输入消失时。 – Bruce

回答

3

当然可以,但你需要手动做一些与文本字段。一般的例程是这样的:有一个TextField后代类,它将有一个可容纳占位符文本的字段。

一个例子:

public class PlaceholderTF extends TextField 
{ 
    private var placeholderText:String; 
    private var currentText:String; 

    public function PlaceholderTF(prompt:String="Input text here") { 
     super(); // making a correct TextField out of ourselves 
     placeholderText = prompt; 
     currentText = ""; 
     AWUTA = false; 
     text = ""; 
    } 

    public override function set text(value:String):void { 
     if (currentText != value) { 
      currentText = value; 

      // calling built-in setter to correctly update text 
      if (currentText == null || currentText == "") { 
       super.text = placeholderText; 
      } else { 
       super.text = currentText; 
      } 
     } 
    } 
} 

该解决方案是相当粗糙的,但可能工作。

+0

谢谢Vesper,但我认为这个解决方案只适用于清除文本提交,但不会移动文本前面的焦点,它甚至可能不存在。 – Bruce

3
var placeholder_text:String = "Search"; 

myTextField.addEventListener(FocusEvent.FOCUS_IN, focusIn); 
myTextField.addEventListener(FocusEvent.FOCUS_OUT, focusOut); 

// fire when click to edit 
function focusIn(event:Event):void 
{ 
    if(myTextField.text == placeholder_text) 
    { 
     myTextField.text = ""; 
    } 
} 

// fire when you clicked out 
function focusOut(event:Event):void 
{ 

    if(myTextField.text == "") 
    { 
     myTextField.text = placeholder_text; 
    } 
}