Use html+css to realize the slow pull-down effect of the menu bar
Goal: Use html+css to achieve the effect that the menu bar will appear slowly when the mouse is moved to the menu bar
We can solve this problem in two ways
Method 1: Transition
-
Turn on
绝对定位
(absolute) for forum-1li
to separate the content from its parent element, otherwise it will squeeze the content to the right, andoverflow:hidden
set the height to 0, and then set the corresponding height after the mouse is moved in..code .forum-1{ /* 开启绝对定位 */ position: absolute; overflow: hidden; height: 0; transition-duration: 0.5s; }
-
The html code is as follows:
<!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>
The css style code is as follows:
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;
}
After trying many times, I found that transition does not support the display attribute, that is to say, you cannot use display: none to hide the menu bar
Method 2: Animation
-
First create the css animation:
@keyframes frames{ from{ height: 0px; } to{ height: 150px; } }
-
Then set display: none to hide the menu style, bind it to the forum-1 selector, bind the animation name with animation, and set the duration
.forum-1{ position: absolute; display: none; overflow: hidden; /* 绑定动画名字并且设置持续时间 */ animation-name: frames; animation-duration: 0.5s; }
-
When the mouse moves in, just set the display property to block
.forum:hover .forum-1{ display: block; }
-
One thing to note is that there will be a problem with the results written in this way: the secondary menu bar will be automatically retracted shortly after the mouse is moved in. In order to avoid this problem, we can add a line of code inside the forum-1 selector:
.forum-1{ animation-fill-mode: forwards; }
The rest of the code is the same as that of Method 1, so I won’t repeat it here
- The renderings are as follows: