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 之间区别的详细信息
归档时间: |
|
查看次数: |
5248 次 |
最近记录: |