目标:利用html+css实现鼠标移到菜单栏时,菜单栏会缓慢出现的效果
我们可以用两种方法来解决这个问题
方法一:过渡(transition)
对forum-1开启绝对定位
(absolute),让里面的li
从其父元素中脱离出去,不然会把之后的内容往右挤,并且设置overflow:hidden
, 设置高度为0, 鼠标移入后再设置相应的高度即可
- .code .forum-1{
- /* 开启绝对定位 */
- position: absolute;
- overflow: hidden;
- height: 0;
- transition-duration: 0.5s;
- }
html 代码如下:
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <link rel="stylesheet" href="./css/index.css">
- <link rel="stylesheet" href="./css/reset.css">
- <title>菜单栏缓慢下拉</title>
- </head>
- <body>
- <ul class="code">
- <li><a href="#">博客</a></li>
- <li class="forum"><a href="#">论坛</a>
- <ul class="forum-1">
- <li><a href="#">css</a></li>
- <li class="vue"><a href="#">vue</a></li>
- <li><a href="#">python</a></li>
- </ul>
- </li>
- <li><a href="#">直播</a></li>
- </ul>
- </body>
- </html>
css 样式代码如下:
- a{
- display: block;
- text-decoration: none;
- color: #333;
- }
- .code{
- width: 390px;
- height: 50px;
- line-height: 50px;
- background-color:#bfa;
- margin: 5px auto;
- }
- .code li{
- float: left;
- width: 130px;
- height: 50px;
- background-color: #bfa;
- text-align: center;
- margin: 0 auto;
- font-size: 20px;
- }
- .code > li:last-child{
- margin-right: 0;
- }
- .code > li:hover{
- background-color: #f8f192;
- }
- .forum{
- position: relative;
- margin: auto 90px;
- }
- .code .forum-1{
- /* 开启绝对定位 */
- position: absolute;
- overflow: hidden;
- height: 0;
- transition-duration: 0.5s;
- }
- .forum:hover .forum-1{
- /* 鼠标移入释放高度 */
- height: 150px;
- }
试了很多次发现,transition是不支持display属性的,也就是说,不能用display:none隐藏菜单栏
方法二:动画(animation)
首先创建css动画:
- @keyframes frames{
- from{
- height: 0px;
- }
- to{
- height: 150px;
- }
- }
然后设置display:none隐藏菜单样式,把它绑定到forum-1选择器中,用animation绑定动画名字,设置持续时间
- .forum-1{
- position: absolute;
- display: none;
- overflow: hidden;
- /* 绑定动画名字并且设置持续时间 */
- animation-name: frames;
- animation-duration: 0.5s;
- }
当鼠标移入时,设置display属性为block即可
- .forum:hover .forum-1{
- display: block;
- }
需要注意的一点是,这样写的结果会出现一个问题:当鼠标移入不久后二级菜单栏会自动收回,为了避免这种问题,我们可以在forum-1选择器内部添加一行代码即可:
- .forum-1{
- animation-fill-mode: forwards;
- }
其余代码和方法一的代码相同,这里不再赘述
效果图如下:

到此这篇关于利用html+css实现菜单栏缓慢下拉效果的示例代码的文章就介绍到这了,更多相关html+css菜单栏缓慢下拉内容请搜索w3xue以前的文章或继续浏览下面的相关文章,希望大家以后多多支持w3xue!