怎么实现鼠标移入第i个li则对应显示第i个div,默认显示第一个LI
html 部分 <ul> <li>菜单1</li> <li>菜单2</li> <li>菜单3</li> <li>菜单4</li> </ul> <dl> <dd>这是内容1</dd> <dd>这是内容2</dd> <dd>这是内容3</dd> <dd>这是内容4</dd> </dl>
css
* { margin: 0; padding: 0; list-style: none; } ul, dl { width: 1080px; margin: 0 auto; overflow: hidden; } li:nth-child(1) { background: #333; } li { width: 25%; text-align: center; line-height: 50px; height: 50px; box-sizing: border-box; border-left: 1px solid #fff; border-right: 1px solid #fff; background: #000; color: #fff; float: left; } dl { position: relative; } dd:nth-child(1) { display: block; } dd { width: 100%; height: 300px; text-align: center; line-height: 300px; font-size: 50px; background: #f2f5f9; display: none; }
js
window.onload = function () { // html 渲染完成后 var li = document.getElementsByTagName('li') // 获取li var dd = document.getElementsByTagName('dd') //获取dd for (let i = 0; i < li.length; i++) { //给每一个li添加鼠标移入事件 li[i].addEventListener('mouseover', function () { //鼠标移入 setDD(i) setLi(i) }) } function setLi(num) { for (var i = 0; i < li.length; i++) { li[i].style.background = "#000" } li[num].style.background = "#333" } function setDD(num) { for (var i = 0; i < dd.length; i++) { dd[i].style.display = "none" } dd[num].style.display = "block" } }