在外部单击时从输入中移除焦点

Remove focus from input on click outside

我正在使用 Flex 4.6 和 spark 组件。我有 DropDownList 表格,我想实现下一个行为:

用户点击 DropDownList 中的文本输入 -> DropDownList 获得焦点

用户在外部点击(例如在背景 Rect 上)-> DropDownList 失去焦点

突然间,第二部分无法在 box 中运行。当用户在文本输入之外单击时,DropDownList 仍然处于焦点状态。如何实现所需的行为?

示例:

<?xml version="1.0"?>
<s:Application xmlns:fx="http://ns.adobe.com/mxml/2009" xmlns:s="library://ns.adobe.com/flex/spark">
    <fx:Script><![CDATA[
        ]]></fx:Script>
    <s:TextInput />
</s:Application>

如果您单击 TextInput,它会获得焦点。并且您无法通过在 TextInput 外部单击来移除此焦点。

首先,我认为您是在谈论 ComboBox spark component and not the DropDownList,因为您提到了组件的 TextInput,在 Label 控件的情况下 DropDownList.

然后,要从 ComboBox 组件移除焦点,您可以在触发组件的更改事件时将 stage.focus 设置为 null

<s:ComboBox change="on_Change(event)" />

protected function on_Change(event:Event):void
{
    stage.focus = null;
}

希望能帮到你。

我在官方论坛找到了解决方法。有一个 post 有同样的问题。 最后的工作解决方案:

textInput.addEventListener(FocusEvent.MOUSE_FOCUS_CHANGE, textInputMouseFocusChange, false, 0, true);
// basically the above Event will dispatch when ever the user clicked outside of textinput when the current focus in in textInput.

private function textInputMouseFocusChange(event:FocusEvent):void {
// basically u dont need this first line if u are not calling any function on textInput focusout.

    textInput.dispatchEvent(new FocusEvent(FocusEvent.FOCUS_OUT));

// the remaing peice of code will remove the current focus from textInput to the area where the user had clicked.
// this piece of code i have taken from one of the comments in the blog : http://blog.flexexamples.com/2008/09/23/setting-focus-in-flex-using-the-focus-manager/

    var focusPoint:Point = new Point();
    focusPoint.x = stage.mouseX;
    focusPoint.y = stage.mouseY;
    var i:int = (stage.getObjectsUnderPoint(focusPoint).length);
    stage.focus=InteractiveObject(stage.getObjectsUnderPoint(focusPoint)[i-1].parent);
}