ExtJs 4给菜单和按钮加上快捷键
Ext.ux.ToolbarKeyMap = Ext.extend(Object, (function() { var kb, owner, mappings; function addKeyBinding(c) { if (kb = c.keyBinding) { delete c.keyBinding; if (!kb.fn && c.handler) { kb.fn = function(k, e) { e.preventDefault(); e.stopEvent(); c.handler.call(c.scope, c, e); } } mappings.push(kb); var t = []; if (kb.ctrl) t.push('Ctrl'); if (kb.alt) t.push('Alt'); if (kb.shift) t.push('Shift'); t.push(kb.key.toUpperCase()); c.hotKey = t.join('+'); c.showHotKey = kb.showHotKey; if (c instanceof Ext.menu.Item) { c.onRender = Ext.Function.createSequence(c.onRender,addMenuItemHotKey); } else if ((c instanceof Ext.Button) && (c.showHotKey)) { c.onRender = Ext.Function.createSequence(c.onRender,addButtonHotKey); } } if ((c instanceof Ext.Button) && c.menu) { c.menu.cascade(addKeyBinding); } } function findKeyNavs() { delete this.onRender; if (owner = this.ownerCt) { mappings = []; this.cascade(addKeyBinding); if (!owner.menuKeyMap) { //owner.menuKeyMap = new Ext.KeyMap(owner.el, mappings); var target = document; if((mappings[0].global!=null)&&(mappings[0].global==false)) { target=owner.el; } owner.menuKeyMap = new Ext.KeyMap(target, mappings); owner.el.dom.tabIndex = 0; } else { owner.menuKeyMap.addBinding(mappings); } } } function addMenuItemHotKey() { delete this.onRender; if((this.showHotKey!=null)&&(this.showHotKey == false)) return; this.el.child('.x-menu-item-link').setStyle({ overflow: 'hidden', zoom: 1 }); this.el.child('.x-menu-item-link').child('.x-menu-item-text').setStyle({ 'float': 'left' }); this.el.child('.x-menu-item-link').createChild({ style: { padding: '0px 0px 0px 15px', float: 'right', }, html: this.hotKey }); } function addButtonHotKey() { delete this.onRender; if((this.showHotKey!=null)&&(this.showHotKey == false)) return; var p = this.btnEl.up(''); p.setStyle({ overflow: 'hidden', zoom: 1 }); if(p.up('td')!=null) p.up('td').setStyle('text-align', 'left'); this.btnEl.setStyle('.x-menu-item-text').setStyle({ 'float': 'left' }); p = p.createChild({ style: { padding: '0px 0px 0px 15px', float: 'right', position: 'relative', bottom: Ext.isWebKit ? '-1px' : '-2px' }, html: this.hotKey }); } return { init: function(toolbar) { toolbar.onRender = Ext.Function.createSequence(toolbar.onRender,findKeyNavs); toolbar.doLayout = Ext.Function.createSequence(toolbar.doLayout,findKeyNavs); } } })());
tbar: { plugins: new Ext.ux.ToolbarKeyMap(), items: [{ text: 'Main Menu', menu: { items: [{ text: 'First option', keyBinding: { key: 'a', ctrl: true }, handler: onMenuClick }, { text: 'Second option', keyBinding: { key: 'c', alt: true }, handler: onMenuClick }] } }, { text: 'A Button', handler: function() { alert("Clicked button"); }, keyBinding: { key: 'd', ctrl: true, alt: true }, showHotKey: true // defaults to NOT showing the hotkey name }] },