jQuery - 右键菜单插件contextMenu使用详解9(使用menu标签构建菜单)
二十、使用 <menu> 标签配置菜单
前面的样例中我们都是直接在 items 属性上配置菜单,其实 contextMenu 也支持 HTML5 的 <menu> 标签。也就是说我们可以在页面上使用 <menu> 标签创建好菜单元素,然后 contextMenu 直接使用它们来生成菜单。
1,效果图
下面是个简单的二级菜单,点击菜单项会弹出相关的信息。

2,样例代码
(1)这里我们使用 <menu> 标签先在页面上创建好菜单,然后再通过 context 加载显示出来。
<button class="context-menu-one">按钮1</button> <menu id="html5menu" style="display:none"> <command label="编辑" icon="edit" onclick="alert('编辑')"> <command label="剪切" icon="cut" onclick="alert('剪切')"> <hr> <menu label="对齐"> <command label="左对齐" onclick="alert('左对齐')"> <command label="右对齐" onclick="alert('右对齐')"> </menu> </menu> <script type="text/javascript"> $(function() { //初始化菜单 $.contextMenu({ selector: '.context-menu-one', items: $.contextMenu.fromMenu($('#html5menu')) }); }); </script>
(2)下面是另外一种写法,大家可以和前面的比较下,可以看到 js 部分简单了许多。
<button class="context-menu-one" contextmenu="html5menu">按钮1</button> <menu id="html5menu" style="display:none" type="context"> <command label="编辑" icon="edit" onclick="alert('编辑')"> <command label="剪切" icon="cut" onclick="alert('剪切')"> <hr> <menu label="对齐"> <command label="左对齐" onclick="alert('左对齐')"> <command label="右对齐" onclick="alert('右对齐')"> </menu> </menu> <script type="text/javascript"> $(function(){ //让老的浏览器也能够支持<menu>标签配置 $.contextMenu('html5'); }); </script>
二十一、<menu> 标签配置菜单项输入控件
使用 <menu> 标签构建菜单时,菜单项除了显示普通文本外,同样也可以配置成输入框、选择框等各种交互控件。
1,效果图
下面我们将这几种类型的控件都显示在一个菜单中。

2,样例代码
<button class="context-menu-one" contextmenu="html5menu">按钮1</button> <menu id="html5menu" style="display:none" type="context"> <label>单行文本输入框<input type="text" name="content"></label> <hr> <label>复选框<input type="checkbox" checked></label> <hr> <label>单选框1<input type="radio" radio="radio" value="1"></label> <label>单选框2<input type="radio" radio="radio" value="2"></label> <label>单选框3<input type="radio" radio="radio" value="3" checked></label> <label>单选框4<input type="radio" radio="radio" value="4" disabled></label> <hr> <select> <option value ="volvo">Volvo</option> <option value ="saab">Saab</option> <option value="opel">Opel</option> <option value="audi">Audi</option> </select> <hr> <label>多行文本输入框<textarea></textarea></label> <hr> <a href="hangge.com">hangge.com</a> </menu> <script type="text/javascript"> $(function(){ //让老的浏览器也能够支持<menu>标签配置 $.contextMenu('html5'); }); </script>