怎么用JS写个下拉菜单

JavaScript021

怎么用JS写个下拉菜单,第1张

其实思路很容易的,先做大导航。然后做下拉菜单,但是下拉菜单默认是display:none当鼠标指向上边的大导航的项目的时候(mouseover),对应的下拉菜单的CSS样式中的display属性设置为block,mouseout的时候又置为none;

<style>

        .clearfix::after {

            display: block

            content: ""

            clear: both

        }

        ul,

        li {

            list-style: none

        }

        .nav>li {

            float: left

            margin: 0 10px

        }

        .nav>li ul {

            display: none

        }

    </style>

</head>

<body>

    <ul class="nav clearfix">

        <li>

            <a href="">微博</a>

            <ul>

                <li>私信</li>

                <li>评论</li>

                <li>@我</li>

            </ul>

        </li>

        <li>

            <a href="">微博</a>

            <ul>

                <li>私信</li>

                <li>评论</li>

                <li>@我</li>

            </ul>

        </li>

        <li>

            <a href="">微博</a>

            <ul>

                <li>私信</li>

                <li>评论</li>

                <li>@我</li>

            </ul>

        </li>

        <li>

            <a href="">微博</a>

            <ul>

                <li>私信</li>

                <li>评论</li>

                <li>@我</li>

            </ul>

        </li>

    </ul>

    <script>

        //案例分析:导航栏里面的li都要有鼠标经过效果 所以需要循环注册鼠标事件

        //核心原理:当鼠标经过li里面的第二个孩子ul显示 当鼠标离开 ul隐藏

        var nav = document.querySelector('.nav')

        var lis = nav.children

        for (var i = 0 i < lis.length i++) {

            lis[i].onmouseover = function() {

                this.children[1].style.display = 'block'

            }

            lis[i].onmouseout = function() {

                this.children[1].style.display = 'none'

            }

        }

    </script>