原生 HTML/CSS/JS 实现右键菜单和二级菜单
以下是使用原生HTML、CSS和JavaScript实现带有二级菜单的右键菜单的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Context Menu Example</title>
<style>
.context-menu {
display: none;
position: absolute;
background-color: #ddd;
border-radius: 5px;
padding: 0;
list-style: none;
}
.context-menu li {
padding: 5px 10px;
cursor: pointer;
}
.context-menu li:hover {
background-color: #bbb;
}
</style>
</head>
<body>
<div id="content">右键点击这里测试右键菜单</div>
<ul class="context-menu" id="contextMenu">
<li data-action="copy">复制</li>
<li data-action="cut">剪切</li>
<li data-action="paste">粘贴</li>
<li data-action="divider">分割线</li>
<li data-action="undo">撤销</li>
<li data-action="redo">重做</li>
<li data-action="submenu" data-submenu="subMenu">更多<ul id="subMenu" style="display: none;">
<li data-action="share">分享</li>
<li data-action="delete">删除</li>
</ul></li>
</ul>
<script>
const contextMenu = document.getElementById('contextMenu');
const content = document.getElementById('content');
// 显示右键菜单
content.addEventListener('contextmenu', function(event) {
event.preventDefault();
contextMenu.style.left = `${event.clientX}px`;
contextMenu.style.top = `${event.clientY}px`;
contextMenu.style.display = 'block';
});
// 隐藏右键菜单
document.addEventListener('click', function() {
contextMenu.style.display = 'none';
});
// 处理菜单项点击事件
contextMenu.addEventListener('click', function(event) {
const target = event.target;
if (target.dataset.action === 'submenu') {
const submenu = document.getElementById(target.dataset.submenu);
submenu.style.display = 'block';
} else if (target.dataset.action === 'divider') {
// 分割线的逻辑
} else {
// 其他菜单项的逻辑
console.log('Action:', target.dataset.action);
}
contextMenu.style.display = 'none';
});
// 处理子菜单项的点击事件
contextMenu.addEventListener('click', function(event) {
const submenu = event.target.closest('[data-submenu]');
if (submenu) {
event.stopPropagation(); // 阻止冒泡,防止隐藏菜单
const action = event.target.dataset.action;
console.log('Submenu Action:', action);
}
});
</script>
</body>
</html>
这段代码实现了一个简单的右键菜单,当用户在指定区域(这里是id为content
的元素)右键点击时显示菜单。菜单项可以包含二级菜单,用户点击二级菜单项时,会在控
评论已关闭