javascript - 下拉菜单隐藏菜单

标签 javascript css

我正在为我正在进行的元素构建一个下拉菜单,但我没有让它完全按预期工作。我希望它在我悬停根级菜单时显示子菜单,然后在菜单或子菜单不再悬停时短暂延迟后再次关闭。大部分都有效;当悬停根级元素时显示子菜单,当我停止悬停根级元素时它隐藏。问题是,当我将光标从根级元素移动到子菜单项不是第一个并将其悬停时,子菜单也被隐藏了。这显然不好,因此我们将不胜感激。

created a JSFiddle使用更清楚地显示问题的代码。

所以,这是我的代码:

菜单.htm

<div id=m_wrapper>
    <ul id=menu>
        <li onMouseOver="show_sub_menu('0')" onMouseOut="start_timer()">Item 1
            <div id=s0 onMouseOver="show_sub_menu('0')" onMouseOut="start_timer()">
                <a href=#>Item 1.1</a>
                <a href=#>Item 1.2</a>
                <a href=#>Item 1.3</a>
            </div>
        </li>
    </ul>
</div>

菜单.css

#m_wrapper {
    position:relative;
    display:table;
}
#menu {
    position:relative;
}
#menu li {
    width:100px;
    position:relative;
    float:left;
    list-style-type:none;
}
#menu div {
    position:absolute;
    visibility:hidden;
    display:inherit;
    width:100%;
    z-index:30
}
#menu div a {
    position:relative;
    display:block;
    z-index:35;
}

menu.js

var countdown = 300;
var timer = null;
var menu_item = null;

window.show_sub_menu = function(cath) {
    if (menu_item) {
        menu_item.style.visibility = 'hidden'; //Make sure to show one menu at a time
    }

    menu_item = window.document.getElementById("s" + cath);
    menu_item.style.visibility = 'visible'; //Show menu

    if (timer) {
        window.clearTimeout(timer); //Reset timer, so menu is kept open
        timer = null;
    }
};

window.start_timer = function() {
    timer = window.setTimeout(close_sub_menu, countdown);
};

window.close_sub_menu = function() {
    menu_item.style.visibility = 'hidden';
};

最佳答案

你不必把它弄得那么复杂。

当然你可以通过 javascript 做同样的事情,但是通过 jQuery 看看它是多么容易、可读和简单。

查看此 DEMO

只需使用以下脚本

$('#menu li').hover(
    function(){
            $(this).stop().animate({height: '100px'},1000,function(){});
            $(this).find('div').show(600);
        }//gets called upon mousehover
    ,
    function(){
            $(this).stop().animate({height: '20px'},1000,function(){});
        } //gets called upon mouseout
  ); //hover ends

而且,我不知道您为什么要编写大量 CSS。只需使用这些:

#menu
{
    list-style:none;
}
#menu li
{
    width:100px;
    border:1px Solid #CCC;
    text-align:Center;
    cursor:pointer;
    height:20px;
    overflow:hidden;

}
#menu li div
{
    border:1px Solid #CCC;
}
#s0 
{
    height:auto;
}
#s0 a
{
    display:block;
}

你可以通过它做很多事情,比如选择下拉项。通过箭头键选择,什么不是。 jQuery 使它变得简单。

关于javascript - 下拉菜单隐藏菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16081297/

相关文章:

javascript - JS数组中每个单词大写的方法

javascript - 如何为 angularjs 路由提供 href

javascript - 使用window.print()时如何添加水印?

html - Bootstrap 颜色范围格式

html - 多背景主页

javascript - 打开引导模式时使第一个选项卡成为事件选项卡

javascript - JQueryUI 可排序的 thead 和 tbody 在拖动隐藏两个字段的行时缩小

javascript - 单击按钮获取 tinyMCE 编辑器实例

css - p :confirmDialog how to change the image and text color

html - 使用 CSS 实现淡入/淡出效果