JavaScript 自动弹出菜单问题
 html文档结构如下:
<body>
   <div>
       <a href="3" class="meauLink" id="meau1">comedies</a>
       <ul class="meau" id="meau2">
           <li><a href="page1.html">All is Well That Ends Well1</a></li>
           <li><a href="page1.html">All is Well That Ends Well2</a></li>
           <li><a href="page1.html">All is Well That Ends Well3</a></li>
           <li><a href="page1.html">All is Well That Ends Well4</a></li>
       </ul>
   </div>
     JS代码:
      function toggleMeau1()
        {
            var link = document.getElementById("meau1");
            var link1 = document.getElementById("meau2").style;
            link.onmouseover = function()
            {
                link1.display = "block";

            }  //鼠标移动到链接上自动打开菜单
            link.parentNode.onmouseout = function()
            {
                link1.display = "none";
            }//鼠标移出层后自动关闭菜单
        }

                问题来了
                鼠标离开链接后自动关闭了菜单,而我的原先设想是鼠标离开层后再自动关闭菜单。用css设置ul的display状态为none。鼠标移动到链接上打开的菜单难道就不算div的吗(这是本问题的重点,希望大神们详细解答下)?为了对比, 我又试了将代码改成进入层自动打开菜单,离开层关闭菜单,能达到鼠标离开层自动关闭菜单的效果。

1个回答

用计时器延时执行隐藏操作,如果移动到菜单上就清楚掉计时器

你这种效果用css就能完毕,不需要用js,麻烦

css下拉菜单

 <div>
    <a href="3" class="meauLink" id="meau1">comedies</a>
    <ul class="meau" id="meau2">
        <li><a href="page1.html">All is Well That Ends Well1</a></li>
        <li><a href="page1.html">All is Well That Ends Well2</a></li>
        <li><a href="page1.html">All is Well That Ends Well3</a></li>
        <li><a href="page1.html">All is Well That Ends Well4</a></li>
    </ul>
</div>
<script>
    function toggleMeau1() {
        var link = document.getElementById("meau1");
        var link1 = document.getElementById("meau2");
        link1.onmouseover = function () {
            clearTimeout(timer);
        }
        link1.onmouseout = function (e) {
            e = e || window.event;
            var o = e.relatedTarget || e.toElement;
            do {
                if (o == this) return;//移动到子元素
            }
            while (o = o.parentNode)

            this.style.display='none'
        }
        link.onmouseover = function () {
            link1.style.display = "block";

        }  //鼠标移动到链接上自动打开菜单
        var timer
        link.onmouseout = function (e) {
            e = e || window.event;
            var o = e.relatedTarget || e.toElement;
            do {
                if (o == this) return;//移动到子元素
            }
            while (o = o.parentNode)

            timer = setTimeout(function () {
                link1.style.display = "none";
            }, 500);

        }//鼠标移出层后自动关闭菜单
    }
    toggleMeau1()
</script>
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!