下拉菜单栏

代码示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
/* 公共样式 */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
html,
body {
width: 100%;
height: 100%;
}
html {
 font-size: 10px;
 }

 /* 页面样式 */
 .nav {
 width: 100%;
 height: 5rem;
 /* 1rem = 10px*/
 background-color: bisque;

 display: flex;
 justify-content: center;
 }

 .content {
 width: 120rem;
 /* background-color:aquamarine; */
 list-style: none;

 display: flex;
 }

 .content .item {
 font-size: 1.8rem;
 height: 100%;
 padding: 0 5rem;
 text-align: center;
 line-height: 5rem;
 cursor: pointer;

 position: relative;
 }

 .content .item:hover {
 background-color: aliceblue;
 color: #333;
 }

 .children {
 list-style: none;
 background-color: antiquewhite;
 position: absolute;
 left: 0;
 top: 5rem;
 display: none;
 }

 .children li {
 padding: 1rem 2rem;
}

 .children li:hover {
 background-color: aquamarine;
 color: #333;
 }
</style>
 </head>

 <body>
 <!-- 背景 -->
<div class="nav">
 <!-- 布局 -->
 <ul class="content">
 <!-- 内容 -->
<li class="item">首页</li>90 <li class="item">文章
 <ul class="children">
 <li>我的文章</li>
 <li>发表文章</li>
 </ul>
 </li>
 <li class="item">相册
 <ul class="children">
 <li>我的相册</li>
 <li>上传照片</li>
 </ul>
 </li>
 <li class="item">消息
 <ul class="children">
 <li>我的私信</li>
 <li>我的留言</li>
 </ul>
 </li>
 </ul>
 </div>

 <script>

 function toggleMenu(parent, is_show) {
 // 让子标签ul.children显示/隐藏
 let child = parent.getElementsByClassName("children")
 if (child.length > 0) {
 // 显示菜单
// console.log(child[0])
 child[0].style.display = is_show }
 }

// 获取所有的一级导航菜单标签
 let _lis = document.getElementsByClassName("item")
 // console.log(_lis)

 // 循环,依次给四个菜单添加单击事件
 for (let i = 0; i < _lis.length; i++) {
    _lis[i].onmouseenter = function () {
 toggleMenu(_lis[i],
"block") // 显示子菜单
 }

 // 添加鼠标离开事件
 _lis[i].onmouseleave = function () {
 toggleMenu(_lis[i],
"none") // 隐藏子菜单
 }
 }
 </script>
 </body>
 </html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容