- html>
- <html lang="en">
-
- <head>
- <meta charset="UTF-8">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <meta http-equiv="X-UA-Compatible" content="ie=edge">
- <title>Documenttitle>
- head>
- <style>
- * {
- padding: 0;
- margin: 0;
- }
-
- ul {
- width: 200px;
- height: 0;
- /* 动画类型 */
- transition: transform;
- /* 动画时长 */
- transition-duration: .8s;
- /* 动画延迟 */
- transition-delay: .2s;
- /* 动画控制属性 */
- transition-property: height;
- overflow: hidden;
- cursor: pointer;
- border-radius: 2px;
- box-shadow: 6px 6px 10px rgba(0, 0, 0, 0.2);
- }
-
- li {
- list-style-type: none;
- width: 200px;
- height: 40px;
- line-height: 40px;
- color: #fff;
- font-size: 14px;
- text-align: center;
- background: #1061f8;
- }
-
- body {
- display: flex;
- flex-direction: column;
- align-items: center;
- }
-
- #btn {
- width: 200px;
- height: 40px;
- line-height: 40px;
- margin-top: 100px;
- text-align: center;
- background: #dfdfdf;
- border-radius: 2px;
- cursor: pointer;
- }
- style>
-
- <body>
- <p id="btn">toggle菜单p>
- <ul id="ul">
- <li>菜单一li>
- <li>菜单一li>
- <li>菜单一li>
- <li>菜单一li>
- <li>菜单一li>
- <li>菜单一li>
- <li>菜单一li>
- <li>菜单一li>
- <li>菜单一li>
- ul>
- body>
- <script>
- var btn = document.getElementById('btn');
- var menu = document.getElementById('ul');
- var heigt = 0
- btn.onmouseenter = function () {
- // 获取菜单高度(执行JS时浏览器来不及渲染,所有不会闪烁)
- if (!heigt) {
- menu.style.height = 'auto';
- heigt = menu.getBoundingClientRect().height;
- }
- menu.style.height = 0;
- //offsetHeight会强制浏览器重绘(先渲染0px,然后再渲染heigt,如果不加则直接会渲染height,不会渲染0px)
- menu.offsetHeight
- menu.style.height = heigt + 'px';
- }
- btn.onmouseleave = function () {
- menu.style.height = 0;
- }
-
- menu.onmouseenter = function () {
- menu.style.height = heigt + 'px';
- }
- menu.onmouseleave = function () {
- menu.style.height = 0;
- }
- script>
-
- html>
