上下文菜单是指在用户交互(例如右键点击)时出现的菜单。 HTML5允许我们自定义此菜单。 这里有一些实现示例,包括嵌套菜单。
示例
HTML
<body contextmenu="share"> <menu type="context" id="share"> <menu label="share"> <menuitem label="Twitter" onclick="shareViaTwitter()"></menuitem> <menuitem label="Facebook" onclick="shareViaFacebook()"></menuitem> </menu> </menu> <ol> <li> Anywhere in the example you can share the page on Twitter and Facebook using the Share menu from your context menu. </li> <li contextmenu="changeFont" id="fontSizing"> On this specific list element, you can change the size of the text by using the "Increase/Decrease font" actions from your context menu </li> <menu type="context" id="changeFont"> <menuitem label="Increase Font" onclick="incFont()"></menuitem> <menuitem label="Decrease Font" onclick="decFont()"></menuitem> </menu> <li contextmenu="ChangeImage" id="changeImage"> On the image below, you can fire the "Change Image" action in your Context Menu.<br /> <img src="https://developer.mozilla.org/media/img/promote/promobutton_mdn5.png" contextmenu="ChangeImage" id="promoButton" /> <menu type="context" id="ChangeImage"> <menuitem label="Change Image" onclick="changeImage()"></menuitem> </menu> </li> </ol> </body>
JavaScript
function shareViaTwitter() { window.open("https://twitter.com/intent/tweet?text=" + "Hurray! I am learning ContextMenu from MDN via Mozilla"); } function shareViaFacebook() { window.open("https://facebook.com/sharer/sharer.php?u=" + "https://developer.mozilla.org/en/HTML/Element/Using_HTML_context_menus"); } function incFont() { document.getElementById("fontSizing").style.fontSize = "larger"; } function decFont() { document.getElementById("fontSizing").style.fontSize = "smaller"; } function changeImage() { var index = Math.ceil(Math.random() * 39 + 1); document.images[0].src = "https://developer.mozilla.org/media/img/promote/promobutton_mdn" + index + ".png"; }
结果
说明
Specification | Status | Comment |
---|---|---|
HTML Living Standard contextmenu |
Living Standard | No change from latest snapshot, HTML 5.1 |
HTML 5.1 contextmenu |
Recommendation | Snapshot of HTML Living Standard, initial definition. |
浏览器兼容性
Feature | Chrome | Firefox (Gecko) | Internet Explorer | Opera | Safari |
---|---|---|---|---|---|
Basic support | 未实现[1] | 9 (9) | 未实现 | 未实现[1] | 未实现 |
Feature | Android | Chrome for Android | Firefox Mobile (Gecko) | IE Mobile | Opera Mobile | Safari Mobile |
---|---|---|---|---|---|---|
Basic support | 未实现 | 未实现 | 20 (20) | 未实现 | 未实现 | ? |
[1]通过命令行选项--enable-blink-features = ContextMenu
可以获得实验性实现。直到Chrome 52和Opera 39之前,它还是一个可选的、实验性功能,但由于Web兼容性问题,现已被删除。在2017年6月,它从这两个浏览器里被完全移除了。这些记录在 Chromium bug 87553。