在上一章里,我们介绍了使用wijmo3的menu给flexgrid做右键菜单。文章阅读:(十一)右键菜单
本文我们就在这个基础上,介绍如何动态的给flexgrid添加右键菜单。本文的右键菜单使用的是input.ListBox。
引用
本文使用wijmo5的ListBox作为右键菜单,除了必要的flexgrid文件,我们还需要在页面引入input.js文件。
参考:
<!--ContextMenu--> <script src="scripts/wijmo.input.min.js" type="text/javascript"></script>
动态创建ListBox
使用createContextMenu方法创建Dom元素,并且初始化为wijmo5的ListBox。
代码参考:
// create a context menu element using a ListBox control function createContextMenu(options, callback) { var menu = document.createElement('div'), lb = new wijmo.input.ListBox(menu); lb.itemsSource = options; lb.selectedIndex = -1; menu.addEventListener('click', function (e) { menu.style.visibility = 'hidden'; callback(lb.selectedItem); lb.selectedIndex = -1; }); menu.addEventListener('keydown', function (e) { if (e.keyCode == wijmo.Key.Escape) { menu.style.visibility = 'hidden'; } }); menu.addEventListener('blur', function (e) { setTimeout(function () { menu.style.visibility = 'hidden'; }, 300); }); return menu; }
调用createContextMenu方法创建右键菜单。
参考:
// create context menu var menu = createContextMenu('New,Open,Close,Save,Save As,Exit'.split(','), function (option) { alert('thanks for selecting option **' + option + '**'); });
右键弹出ListBox
获取flexgrid的Dom元素,并且通过事件监听,将Listbox在右键菜单的时候展示出来。
var element = document.getElementById('gsFlexGrid'); element.addEventListener('contextmenu', function (e) { e.preventDefault(); showPopup(menu, e); });
此处使用了showPopup方法,该方法控制Dom元素的展示和焦点。
代码如下:
// show an element as a popup function showPopup(popup, ref) { // make sure popup is a child of the body if (!popup.parentElement) { document.body.appendChild(popup); } // calculate popup position var sz = popup.getBoundingClientRect(), left = ref.clientX - sz.width / 2, top = ref.clientY - sz.height / 2; // make sure popup is visible left = Math.max(0, Math.min(left, innerWidth - sz.width)); top = Math.max(0, Math.min(top, innerHeight - sz.height)); // show the popup wijmo.setCss(popup, { position: 'absolute', left: left + pageXOffset, top: top + pageYOffset, visibility: 'visible' }); // focus on the popup popup.focus(); }
本文的演示效果如图:
本文的演示代码请下载:flexgrid_DymanicContextMenu.zip (88.69 kb)
如果你对Wijmo5感兴趣,可以到如下链接下载:
更多资源:
Wijmo中文官网:/developer/wijmojs
Wijmo5在线示例:/developer/wijmojscore
Wijmo5产品文档:/developer/wijmojscore
如果依然有问题,可以到我们的官方产品论坛发帖咨询:http://gcdn.grapecity.com.cn/showforum-140.html
请参考Wijmo5技术文章汇总
《wijmo5 flexgrid基础教程》系列文章