Skip to content

Commit

Permalink
✨ (Header.astro): replace dropdown div with details and summary eleme…
Browse files Browse the repository at this point in the history
…nts for better semantics and accessibility

💡 (Header.astro): add script to close dropdown menu when clicking outside or selecting an option for improved user experience
  • Loading branch information
yaotutu committed Sep 14, 2024
1 parent 197e7c0 commit 48da6b9
Showing 1 changed file with 33 additions and 4 deletions.
37 changes: 33 additions & 4 deletions src/components/Header.astro
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ import { SITE_TITLE } from "../consts";
class="navbar max-md:translate-y-0 fixed px-2 w-full transform -translate-y-full text-center z-50 transition-transform bg-base-100 shadow-xl"
>
<div class="navbar-start">
<div class="dropdown">
<div
<details class="dropdown" id="dropdown">
<summary
tabindex="0"
role="button"
class="btn btn-ghost"
Expand All @@ -25,9 +25,9 @@ import { SITE_TITLE } from "../consts";
d="M64,384H448V341.33H64Zm0-106.67H448V234.67H64ZM64,128v42.67H448V128Z"
></path></svg
>
</div>
</summary>
<Menu />
</div>
</details>
</div>
<div class="navbar-center">
<a class="btn btn-ghost text-xl" href="/">{SITE_TITLE}</a>
Expand Down Expand Up @@ -59,3 +59,32 @@ import { SITE_TITLE } from "../consts";
</div>
</div>
</div>
<script>
// 当用户点击菜单区域外部区域的时候, 关闭菜单
document.addEventListener("click", function (event) {
const dropdown = document.getElementById("dropdown") as HTMLElement;
const isClickInside = dropdown.contains(event.target as Node);
if (!isClickInside && dropdown.hasAttribute("open")) {
dropdown.removeAttribute("open");
}
});

// 当用户滑动菜单区域外部区域的时候, 关闭菜单
document.addEventListener("touchmove", function (event) {
const dropdown = document.getElementById("dropdown") as HTMLElement;
const isTouchInside = dropdown.contains(event.target as Node);
if (!isTouchInside && dropdown.hasAttribute("open")) {
dropdown.removeAttribute("open");
}
});

// 当用户点击菜单的具体的选项的时候, 关闭菜单
document.querySelectorAll("#dropdown > ul > li").forEach((item) => {
item.addEventListener("click", function () {
const dropdown = document.getElementById("dropdown") as HTMLElement;
if (dropdown.hasAttribute("open")) {
dropdown.removeAttribute("open");
}
});
});
</script>

0 comments on commit 48da6b9

Please sign in to comment.