使用 Alpine JS 将鼠标悬停在下拉菜单上

Red*_*edZ 7 html javascript alpine.js

我想构建一个在鼠标悬停时显示并显示元素的菜单:类别:-子类别1-子类别2

我设法做到了这一点,但我的问题是,当我将鼠标悬停在菜单上并显示里面的元素并且我将鼠标移离菜单本身时,元素不会隐藏。

这是我的代码:

<div x-data="{open: false}">
    <button @mouseover="open = true">Category</button>
    <div x-show="open" @mouseout="open = false" class="h-80 bg-red-900">
        <ul>
            <li>Sub-category 1</li>
            <li>Sub-category 2</li>
        </ul>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

OLI*_*ERS 16

不要使用mouseout事件。而是用mouseleave在外面。div

这是对我来说效果很好的解决方案。

<div x-data="{ open: false }" class="ml-4" @mouseleave="open = false">
        <button @mouseover="open = true" class="border border-primary-900">Category</button>
        <div x-show="open" class="h-80 bg-red-900">
            <ul>
                <li>Sub-category 1</li>
                <li>Sub-category 2</li>
            </ul>
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)

例子 :

下面的示例说明了 mouseout 和 mouseleave 事件之间的区别。mouseleave 事件被添加到 中,<ul>以便每当鼠标退出 时将列表着色为紫色<ul>。mouseout 被添加到列表中,以便在鼠标退出时将目标元素着色为橙色。

当您尝试此操作时,您会发现 mouseout 被传递到各个列表项,而 mouseleave 则传递到整个列表,这是由于项目的层次结构以及列表项遮盖了底层 .

<div x-data="{ open: false }" class="ml-4" @mouseleave="open = false">
        <button @mouseover="open = true" class="border border-primary-900">Category</button>
        <div x-show="open" class="h-80 bg-red-900">
            <ul>
                <li>Sub-category 1</li>
                <li>Sub-category 2</li>
            </ul>
        </div>
    </div>
Run Code Online (Sandbox Code Playgroud)
let test = document.getElementById("test");

// Briefly make the list purple when the mouse moves off the
// <ul> element
test.addEventListener("mouseleave", function( event ) {
  // highlight the mouseleave target
  event.target.style.color = "purple";

  // reset the color after a short delay
  setTimeout(function() {
    event.target.style.color = "";
  }, 1000);
}, false);

// Briefly make an <li> orange when the mouse moves off of it
test.addEventListener("mouseout", function( event ) {
  // highlight the mouseout target
  event.target.style.color = "orange";

  // reset the color after a short delay
  setTimeout(function() {
    event.target.style.color = "";
  }, 500);
}, false);
Run Code Online (Sandbox Code Playgroud)

来源:您可以查看更多有关mouseout 和 mouseleave 之间区别的详细信息


Chr*_*eve 8

@mouseover.away = "open = false"在外面的div

  • 这只是因为你希望它在外部 div 之外关闭 (2认同)