2011-02-08 88 views
1

我想在按下向上箭头时关注TextField的结尾。我使用的是:AS3:setSelection向上箭头覆盖

txt.setSelection(txt.text.length,txt.text.length); 

这对于除向上箭头任意键的伟大工程。我相信,当向上箭头对焦时,它会自动将选择设置为TextField的开头。我如何覆盖这种默认行为?

回答

5

我想改变Home键的行为,这是我做的:
(下面的代码基本上应禁用HOME键,但可以进行修改,以使其做任何事情)

// Create two variables two remember the TextField's selection 
// so that it can be restored later. These varaibles correspong 
// to TextField.selectionBeginIndex and TextField.selectionEndIndex 
var overrideSelectionBeginIndex:int = -1; 
var overrideSelectionEndIndex:int; 

// Create a KEY_DOWN listener to intercept the event -> 
// (Assuming that you have a TextField named 'input') 
input.addEventListener(KeyboardEvent.KEY_DOWN, event_inputKeyDown, false, 0, true); 

function event_inputKeyDown(event:KeyboardEvent):void{ 
    if(event.keyCode == Keyboard.HOME){ 
     if(overrideSelectionBeginIndex == -1){ 
      stage.addEventListener(Event.RENDER, event_inputOverrideKeyDown, false, 0, true); 
      stage.invalidate(); 
     } 

     // At this point the variables 'overrideSelectionBeginIndex' 
     // and 'overrideSelectionEndIndex' could be set to whatever 
     // you want but for this example they just store the 
     // input's selection before the home key changes it. 
     overrideSelectionBeginIndex = input.selectionBeginIndex; 
     overrideSelectionEndIndex = input.selectionEndIndex; 
    } 
} 

// Create a function that will be called after the key is 
// pressed to override it's behavior 
function event_inputOverrideKeyDown(event:Event):void{ 
    // Restore the selection 
    input.setSelection(overrideSelectionBeginIndex, overrideSelectionEndIndex); 

    // Clean up 
    stage.removeEventListener(Event.RENDER, event_inputOverrideKeyDown); 
    overrideSelectionBeginIndex = -1; 
    overrideSelectionEndIndex = -1; 
} 
0

有可以应用到行动,它取消(我假定这将是)的Prevent Default (livedocs)功能,否则,你可以尝试用stopPropagation,而不是抓住它:

此处理不当进行了测试,而应该看是这样的:

function buttonPress(ev:KeyboardEvent):void{ 
    txt.setSelection(txt.text.length,txt.text.length); 
    ev.preventDefault(); 
} 
+0

我今天发布了一个类似的答案,但我已经删除了它。在这种情况下`preventDefault()`方法不起作用。 `stopPropagation()`也不起作用。我测试了他们两个。顺便说一下,有一次类似的问题:http://stackoverflow.com/questions/1018259/how-do-you-prevent-arrow-up-down-default-behaviour-in-a-textfield和OP有还说他试过`preventDefault()`和`stopImmediatePropagation()`,但都没有为他工作(我只是不明白他为什么接受答案,因为它仍然不适合他 - 对我也是如此) 。 – rhino 2011-02-08 16:18:11

+0

有没有解决方法? – Abdulla 2011-02-08 22:43:24