简体   繁体   English

菜单本应隐藏onmouseout,但会隐藏onmouseover

[英]Menu supposed to hide onmouseout but it hide onmouseover

I have a button and a menu. 我有一个按钮和一个菜单。 The button on mouse over shows the menu. 鼠标悬停在按钮上显示菜单。 I've coded when the mouse leaves the menu to hide itself, but it hides before the mouse goes over it. 我已经编码了鼠标离开菜单以隐藏自身的时间,但是它在鼠标经过菜单之前就隐藏了。 Help? 救命?

 function showMenu() { var menuBar = document.getElementById("menu"); menuBar.style.display = "block"; } function hideMenu() { document.getElementById("menu").style.display = "none"; } 
 <a id="menu_button" onmouseover="showMenu()"><img src="https://i.imgur.com/mRIyhW8.png" class="menu_button" onmouseover="this.src='https://i.imgur.com/zSPpoVX.png'" onmouseout="this.src='https://i.imgur.com/mRIyhW8.png'" /></a> <div id="menu" onmouseout="hideMenu()"> <ul> <li>HOME</li> <li>PORTFOLIO</li> <li>ABOUT</li> </ul> </div> 

EDIT Adding a z-index: 2; 编辑添加一个z-index:2; in my css solved the problem. 在我的CSS解决了问题。 Thank you for your time. 感谢您的时间。

onmouseout event is triggered when the mouse over the UL element. 当鼠标悬停在UL元素上时,会触发onmouseout事件。 It it complex to solve this problem with pure javascript. 使用纯JavaScript解决此问题很复杂。 Jquery has mouseenter and mouseleave methods. jQuery具有mouseenter和mouseleave方法。

    $("#menu_button").mouseenter(function () {
        $("#menu").show();
    });
    $("#menu").mouseleave(function () {
        $(this).hide();
    });

You need to use mouseleave because: 您需要使用mouseleave因为:

The mouseout event triggers when the mouse pointer leaves any child elements as well the selected element. 当鼠标指针离开任何子元素以及所选元素时,将触发mouseout事件。

Update: 更新:

  1. changed the size of the menu_button to avoid triggering outside the image. 更改了menu_button的大小,以避免在图像外部触发。
  2. Added css to #menu, now starts hidden. 在#menu中添加了CSS,现在开始隐藏。
  3. Added a mouseleave to menu_button to hide when leaving the image. 增加了一个mouseleavemenu_button离开图像时隐藏。

 document.getElementById("menu_button").addEventListener('mouseover', function() { document.getElementById("menu").style.display = "block"; }); document.getElementById("menu").addEventListener('mouseover', function() { document.getElementById("menu").style.display = "block"; }); document.getElementById("menu").addEventListener('mouseleave', function() { document.getElementById("menu").style.display = "none"; }); document.getElementById("menu_button").addEventListener('mouseleave', function() { document.getElementById("menu").style.display = "none"; }); 
 #menu_button { display: block; width: 50px; height: 50px; } #menu_button img:hover { opacity: 0.8; } #menu { border: solid 1px; display: none; } 
 <a id="menu_button"><img src="https://i.imgur.com/mRIyhW8.png" class="menu_button" /></a> <div id="menu"> <ul> <li>HOME</li> <li>PORTFOLIO</li> <li>ABOUT</li> </ul> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM