我有一个网页,使用 Alpine.js 和 Focus Plugin 在单击某个项目时打开模式,我还希望能够使用空格键打开模式并输入键
它可以工作,但是当使用回车键时,它似乎再次触发对模式的点击,并且它现在重新打开
这是代码:
<div x-data="{ open: false }">
<div class="mt-8 grid grid-cols-3 gap-8 mx-auto max-w-4xl">
<div
class="aspect-square rounded bg-gray-300 grid place-items-center font-bold text-3xl"
@click="open = 1"
@keyup.enter="open = 1"
@keyup.space="open = 1"
tabindex="0"
>1</div>
<div
class="aspect-square rounded bg-gray-300 grid place-items-center font-bold text-3xl"
@click="open = 2"
@keyup.enter="open = 2"
@keyup.space="open = 2"
tabindex="0"
>2</div>
<div
class="aspect-square rounded bg-gray-300 grid place-items-center font-bold text-3xl"
@click="open = 3"
@keyup.enter="open = 3"
@keyup.space="open = 3"
tabindex="0"
>3</div>
</div>
<div
id="modal"
class="bg-black/50 fixed top-0 left-0 w-full h-full p-4 grid place-items-center z-10"
x-show="open"
x-cloak
x-trap.inert="open != 0"
x-transition.opacity
>
<div class="modal__body bg-white max-w-[760px] p-8 relative" x-transition.delay.50ms>
<button
type="button"
class="font-bold uppercase"
@click="open = false"
@keyup.enter="open = false"
@keyup.space="open = false"
tabindex="0"
>
Close
</button>
<div>Modal content</div>
</div>
</div>
</div>
我准备了一个简单的 CodePen 来查看问题,只需 Tab 到任何元素并按 Enter 键打开模式,然后按 Enter 键关闭
<button>
元素会在按键的 click
上自动触发 Enter 或 Space 按键的 keydown
事件。
因此,当在模态框的关闭按钮上按下 Enter 或 Space 时,模态框将关闭。但是,焦点随后返回到
<div>
,并且当释放 Enter 或 Space 键时,会激活 keyup
事件侦听器。
要解决此问题,您可以考虑监听
keydown
而不是 <div>
元素:
<script defer src="https://cdn.jsdelivr.net/npm/@alpinejs/[email protected]/dist/cdn.min.js"></script>
<script defer src="https://cdn.jsdelivr.net/npm/[email protected]/dist/cdn.min.js"></script>
<script src="https://cdn.tailwindcss.com/3.3.3"></script>
<div x-data="{ open: false }">
<div class="mt-8 grid grid-cols-3 gap-8 mx-auto max-w-4xl">
<div
class="aspect-square rounded bg-gray-300 grid place-items-center font-bold text-3xl"
@click="open = 1"
@keydown.enter="open = 1"
@keydown.space="open = 1"
tabindex="0"
>1</div>
<div
class="aspect-square rounded bg-gray-300 grid place-items-center font-bold text-3xl"
@click="open = 2"
@keydown.enter="open = 2"
@keydown.space="open = 2"
tabindex="0"
>2</div>
<div
class="aspect-square rounded bg-gray-300 grid place-items-center font-bold text-3xl"
@click="open = 3"
@keydown.enter="open = 3"
@keydown.space="open = 3"
tabindex="0"
>3</div>
</div>
<div
id="modal"
class="bg-black/50 fixed top-0 left-0 w-full h-full p-4 grid place-items-center z-10"
x-show="open"
x-cloak
x-trap.inert="open != 0"
x-transition.opacity
>
<div class="modal__body bg-white max-w-[760px] p-8 relative" x-transition.delay.50ms>
<button
type="button"
class="font-bold uppercase"
@click="open = false"
tabindex="0"
>
Close
</button>
<div>Modal content</div>
</div>
</div>
</div>