当按下向上箭头时,我想关注TextField的结尾。我正在使用:
txt.setSelection(txt.text.length,txt.text.length);
这适用于除向上箭头之外的任何键。我相信当箭头处于焦点时,向上箭头会自动将选择设置为TextField的开头。如何覆盖此默认行为?
答案 0 :(得分:5)
我想改变主页键的行为,这就是我做的方式:
(以下代码实际上应禁用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;
}
答案 1 :(得分:0)
如果可以取消,我可以对该动作应用Prevent Default (livedocs)函数(我认为它会是这样),否则你可以尝试用stopPropagation来捕捉它:
这还没有经过测试,但应该看起来像:
function buttonPress(ev:KeyboardEvent):void{
txt.setSelection(txt.text.length,txt.text.length);
ev.preventDefault();
}