Skip to content

Commit

Permalink
完善弹出菜单的位置
Browse files Browse the repository at this point in the history
  • Loading branch information
qichunren committed Oct 5, 2024
1 parent 91f2db0 commit 67969ac
Showing 1 changed file with 20 additions and 3 deletions.
23 changes: 20 additions & 3 deletions demo/PopupMenu.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
list-style-type: none;
padding: 0;
margin: 0;
z-index: 1000;
}
.menu[aria-hidden="false"] {
display: block;
Expand All @@ -21,15 +22,16 @@
padding: 8px 16px;
cursor: pointer;
}
.menu-item:focus {
.menu-item:focus,
.menu-item:hover {
background-color: #e5e5e5;
outline: none;
}
</style>
</head>
<body>

<button id="menuButton" aria-haspopup="true" aria-expanded="false">Open Menu</button>
<button id="menuButton" aria-haspopup="true" aria-expanded="false" style="position: absolute;left: 400px;top: 300px;">Open Menu</button>

<ul id="menu" class="menu" role="menu" aria-hidden="true">
<li class="menu-item" role="menuitem" tabindex="-1">Item 1</li>
Expand All @@ -50,12 +52,23 @@
menuButton.setAttribute('aria-expanded', menuOpen);

if (menuOpen) {
positionMenu(); // Position the menu next to the button
menuItems[0].focus(); // Focus on the first menu item
} else {
menuButton.focus(); // Return focus to the button
}
}

// Function to position the menu next to the button
function positionMenu() {
const buttonRect = menuButton.getBoundingClientRect();
const menuTop = buttonRect.bottom + window.scrollY;
const menuLeft = buttonRect.left + window.scrollX;

menu.style.top = `${menuTop}px`;
menu.style.left = `${menuLeft}px`;
}

// Event listener for button click
menuButton.addEventListener('click', () => {
toggleMenu();
Expand All @@ -72,7 +85,7 @@
// Keyboard navigation within the menu
menu.addEventListener('keydown', (event) => {
let currentIndex = menuItems.indexOf(document.activeElement);

if (event.key === 'ArrowDown') {
event.preventDefault();
currentIndex = (currentIndex + 1) % menuItems.length;
Expand All @@ -83,6 +96,10 @@
menuItems[currentIndex].focus();
} else if (event.key === 'Escape') {
toggleMenu();
} else if (event.key === 'Tab') {
event.preventDefault();
currentIndex = (currentIndex + 1) % menuItems.length;
menuItems[currentIndex].focus();
}
});

Expand Down

0 comments on commit 67969ac

Please sign in to comment.