js使用面向对象编写下拉菜单

<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>无标题文档</title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
            list-style: none;
        }

        .all {
            width: 330px;
            height: 30px;
            background: url(img/bg.jpg) no-repeat;
            margin: 100px auto;
            line-height: 30px;
            text-align: center;
            padding-left: 10px;
            margin-bottom: 0;
        }

        .all ul li {
            width: 100px;
            height: 30px;
            background: url(img/libg.jpg);
            float: left;
            margin-right: 10px;
            position: relative;
            cursor: pointer;
        }

        .all ul ul {
            position: absolute;
            left: 0;
            top: 30px;
            display: none;
        }
    </style>
</head>

<body>
    <div class="all">
        <ul id="list">
            <li>一级菜单
                <ul>
                    <li>二级菜单</li>
                    <li>二级菜单</li>
                    <li>二级菜单</li>
                </ul>
            </li>
            <li>一级菜单
                <ul>
                    <li>二级菜单</li>
                    <li>二级菜单</li>
                    <li>二级菜单</li>
                </ul>
            </li>
            <li>一级菜单
                <ul>
                    <li>二级菜单</li>
                    <li>二级菜单</li>
                    <li>二级菜单</li>
                </ul>
            </li>
        </ul>
    </div>
</body>

</html>
<script>
    window.onload = function () {
        new ListMenu().init();
    }

    function ListMenu() {
        this.list = list.children;
        this.init = function () {
            for (let i = 0; i < this.list.length; i++) {
                this.list[i].onmouseenter = function () {
                    this.show(this.list[i].children[0]);
                }.bind(this)
                this.list[i].onmouseleave = function () {
                    this.hide(this.list[i].children[0]);
                }.bind(this)
            }
        }
        this.show = function (obj) {
            obj.style.display = "block";
        }
        this.hide = function (obj) {
            obj.style.display = "none";
        }
    }
</script>

猜你喜欢

转载自www.cnblogs.com/1512344358qq/p/10364585.html