首先要获取它的标签  之后让鼠标进入box 显示二级菜单ul,然后通过事件委托绑定在父元素之上,不是给li标签一个一个绑定!减少代码的冗余,

效果展示:

 

 css代码:

 .box {
        border: 1px solid #000;
        display: inline-block;
      }
      ul,
      li {
        list-style: none;
        margin: 0;
        padding: 0px;
        border: 1px solid #000;
      }
      li.active {
        background-color: #ccc;
      }
      ul {
        display: none;
      }

html代码:

<div class="box">
      <input id="txt" placeholder="请选择游戏名称" />
      <ul>
        <li class="active">LOL</li>
        <li>CSGO</li>
        <li>CF10年老兵</li>
        <li>GTA</li>
        <li>农药</li>
      </ul>
</div>

script代码:

var oBox = document.querySelector(".box");
      var oTxt = document.querySelector("#txt");
      var oUl = oBox.children[1];

      //鼠标进入box,让ul显示
      oBox.onmouseenter = function () {
        oUl.style.display = "block";
      };
      oBox.onmouseleave = function () {
        oUl.style.display = "none";
      };
      // 事件委托的好处,减少事件绑定带来开销问题
      oBox.onmouseover = function (e) {
        console.log(e.target);
        var { target } = e;
        if (target.nodeName != "LI") {
          return;
        }
        var oLis = target.parentNode.children;
        for (var i = 0; i < oLis.length; i++) {
          oLis[i].className = "";
        }
        target.className = "active";
      };

      //事件委托
      oBox.onclick = function (e) {
        var { target } = e;
        if (target.nodeName != "LI") {
          return;
        }
        oTxt.value = target.innerText;
        target.parentNode.style.display = "none";
      };

版权声明:本文为qq_56244419原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
原文链接:https://blog.csdn.net/qq_56244419/article/details/127309824