每个网站都包含导航条菜单,在此做一些 HTML 和 CSS 基础回顾。
本文主要跟随课程完成导航栏菜单的制作,课程来源 imooc导航条菜单的制作。
推荐学习前端的朋友可以看看,简简单单一个小课程,对于刚有前端基础的人来说很友好,整体清晰易懂,逻辑通顺,后期稍微涉及一丢丢 JS,很不错。
垂直菜单栏
导航菜单用什么元素制作呢,通过之前学习的网页设计结构表现原则我们可以得知,导航目录条目性的语义 与 无序列表 非常接近,所以选用无序列表。
垂直菜单栏的整体结构如下:
HTML 代码:
1 2 3 4 5 6 7 8 9
| <body> <ul> <li><a href="#">首页</a></li> <li><a href="#">新闻快讯</a></li> <li><a href="#">产品展示</a></li> <li><a href="#">售后服务</a></li> <li><a href="#">联系我们</a></li> </ul> </body>
|
CSS 样式:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| * { margin: 0; padding: 0; font-size: 14px; } ul { list-style: none; width: 100px; } a { text-decoration: none; display: block; height: 30px; line-height: 30px; width: 100px; background-color: #ccc; margin-bottom: 1px; text-indent: 10px; } a:hover { background-color: #f60; color: #fff; }
|
实现垂直菜单栏效果如下:
水平菜单栏
水平菜单栏如何制作,将垂直放平就是了,所以给 li 添加浮动,浮动后,我们将 ul 的宽度删掉,使 ul 宽度自己被撑起。
接下来对 a 链接文字位置修改居中即可,改动如下:
CSS 样式:
1 2 3 4 5 6 7 8 9 10
| ul { list-style: none; } li { float: left; } a { ... text-align: center; }
|
水平菜单栏效果图如下:
伸缩菜单栏-改变高度
要求:当鼠标经过菜单项的时候,菜单的高度发生了变化。
首先想到的肯定是在:hover 的状态下改变 height。我们进行尝试。
1 2 3 4
| a:hover { ... height: 40px; }
|
我们发现样式没有达到我们想要的向上增高的效果,那我们如何实现呢?
采用 margin-top:负值 的方法去实现。然后将文字的 line-height 修改正确即可。
代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| ul { list-style: none; height: 50px; padding-left: 30px; border-bottom: 5px solid #f60; } li { float: left; margin-top: 20px; } a { text-decoration: none; display: block; height: 30px; line-height: 30px; width: 120px; background-color: #ccc; margin-bottom: 1px; text-align: center; } a:hover { background-color: #f60; color: #fff; margin-top: -10px; height: 40px; line-height: 40px; }
|
菜单栏水平伸缩
水平伸缩,采用 JavaScript 脚本实现,JS 代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| window.onload = function () { var aA = document.getElementsByTagName("a"); for (var i = 0; i < aA.length; i++) { aA[i].onmouseover = function () { var This = this; This.time = setInterval(function () { This.style.width = This.offsetWidth + 8 + "px"; if (This.offsetWidth > 160) { clearInterval(This.time); } }, 30); }; aA[i].onmouseout = function () { var This = this; This.time = setInterval(function () { This.style.width = This.offsetWidth - 8 + "px"; if (This.offsetWidth <= 120) { clearInterval(This.time); } }, 30); }; } };
|
效果如下:
总结
- Q: 通常用什么构建导航条菜单?
- A: 使用无序列表。
- Q: 如何将垂直菜单变为水平?
- A: 使用 float: left;
- Q: 制作改变高度延伸,用什么实现?
- A: 使用 margin-top: 负值;
- Q: JS 改变水平宽度时,this 表示什么?
- A: 表示当前 dom 元素,即 a 元素。