我在as3上有关于文本字段占位符的快速提问。
所有现代浏览器或移动应用都支持文本输入字段的占位符。一旦你点击它,焦点移动到文本的开头,占位符保持不变,直到你开始输入。
只是想知道这是否可以在as3上实现?
干杯 比尔
答案 0 :(得分:3)
当然,但您需要手动对TextField执行某些操作。一般例程是这样的:有一个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;
}
}
}
}
这个解决方案很粗糙,但可能有用。
答案 1 :(得分: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;
}
}
答案 2 :(得分:0)
这是一个适用于我的表单验证示例:
package components {
import flash.events.Event;
import flash.events.FocusEvent;
import flash.text.TextField;
public class TextFieldPlaceholder extends TextField {
private var _placeholderText:String;
private var _currentText:String;
public function TextFieldPlaceholder(placeholderText:String = 'Input text here') {
_placeholderText = placeholderText;
_currentText = '';
this.addEventListener(FocusEvent.FOCUS_OUT, onFocusOut);
this.addEventListener(FocusEvent.FOCUS_IN, onFocusIn);
super();
}
override public function get text():String {
if (_currentText == _placeholderText) {
return '';
}
return _currentText;
}
override public function set text(value:String):void {
_currentText = value;
if (!_currentText) {
super.text = _placeholderText;
} else {
super.text = _currentText;
}
}
private function onFocusIn(e:Event):void {
super.text = _currentText;
}
private function onFocusOut(e:Event):void {
this.text = super.text;
}
}
}