2014-01-19 50 views
0

我有一个菜单,这个菜单中的某些项目有子菜单。我想让子菜单在鼠标移过时保持打开状态

我使用XHTML + CSS创建主菜单和子菜单,同时我使用native javascript来显示和隐藏子菜单,当用户将鼠标移动到具有子菜单的项目上时。

将鼠标移动到包含子菜单的项目时,出现子菜单,但是当将鼠标光标移动到子菜单时,子菜单消失。

我要的是,子菜单保持可见,如果将鼠标光标在主菜单或项目的项目,在子菜单

HTML

<div class="box"> 
<ul> 
    <li class="havSub">Item 1 
     <div> 
      <ul> 
       <li> <a href="#"> Sub 1 </a> </li> 
       <li> <a href="#"> Sub 2 </a> </li> 
      </ul> 
     </div> 
    </li> 
    <li> <a href="#"> Item 2 </a> </li> 
    <li> <a href="#"> Item 3 </a> </li> 
    <li class="havSub">Item 4 
     <div> 
      <ul> 
       <li> <a href="#"> Sub 1 </a> 
       </li> 
       <li> <a href="#"> Sub 2 </a> 
       </li> 
      </ul> 
     </div> 
    </li> 
    <li> <a href="#"> Item 5 </a> 
    </li> 
</ul> 

CSS

.box{width:150px; border:2px solid #ccc; text-align:center; margin-top:50px;} 
.box ul {padding:0; margin:0; list-style-type:none;} 
.box ul li {margin-bottom:1px; display:block; padding:5px; background-color:#fff000; color:#ff0000; font:bold 20px arial; cursor:pointer;} 
.box ul li:hover {background-color:#ffff00; color:#ff0000;} 
.box ul li a {display:block; color:#ff0000; font:bold 20px arial; text-decoration:none;} 
.box ul li div {position:relative; left:145px; top:-29px; display:none;} 
.box ul li div ul {position:absolute;} 

的Javascript

document.addEventListener('mouseover', function (event) { 
    event = (event) ? event : window.event; 
    if (event.target.className === 'havSub') { 
     event.target.children.item(0).style.display = 'block'; 
     event.target.addEventListener("mouseout", function() { 
      event.target.children.item(0).style.display = 'none'; 
     }); 
    } 
}); 

你可以看到JSFiddle demo

+0

为什么不只是使用jQuery的菜单,并完成它呢? –

+1

你应该在问题本身中包含你的相关代码,以便在jsFiddle关闭的情况下有价值 –

+0

@LayTaylor:我比jquery更喜欢原生JavaScript。 –

回答

2

可以解决这个问题很容易,同时通过使用下面的代码

.box ul li:hover * { 
    display:block; 
} 

Demo

不再需要的jQuery

它适用于支持CSS2任何浏览器,所以IE7 +

+0

谢谢,但是'*'符号的含义在这里? –

+0

在这种情况下,它意味着'li'下的所有孩子。基本上它是CSS“所有”选择器。有关CSS选择器的更多信息,请查看[这篇有用的文章](http://net.tutsplus.com/tutorials/html-css-techniques/the-30-css-selectors-you-must-memorize/) –

0

如果你正在寻找一个更兼容的解决方案,这意味着服务于IE6,这里的问题的核心:

子菜单上的大火链接主菜单的onmouseout事件。您可以在DOM对象上放置一个标志来安排推迟的onmouseout。当在子菜单上检测到onmouseover事件时,定时器事件被取消。关闭菜单的责任现在被转发到子菜单。

$('main').onmouseout=function(){ 
    this.closing=setTimeout(function(){ 
     //close the menu here 
    },300); //allow enough time to move on to the sub menu 
} 

$('sub').onmouseover=function(){ 
    //cancel the closing event 
    if ($('main').closing) clearTimeout($('main').closing); 

    this.onmouseout=function(){ 
     //close the menu here 
    } 
} 
相关问题