该问题的解决方法是给包含菜单的元素添加一个固定的高度,并将菜单元素的高度设置为0。然后,在菜单按钮被点击时,使用JavaScript来动态地将菜单元素的高度设置为固定值。这样,就可以使用translateY属性来控制菜单的垂直位置,从而实现平滑的菜单过渡效果。以下是代码示例:
HTML代码:
CSS代码:
.menu-container {
position: relative;
height: 50px;
}
.menu {
position: absolute;
top: 100%;
left: 0;
width: 100%;
height: 0;
overflow: hidden;
background-color: #fff;
box-shadow: 0 4px 10px rgba(0, 0, 0, 0.2);
transition: height 0.3s ease-in-out;
}
.menu.active {
height: 150px;
}
.menu li {
list-style: none;
padding: 10px;
font-size: 16px;
color: #333;
cursor: pointer;
}
.menu-btn {
display: flex;
align-items: center;
justify-content: center;
width: 50px;
height: 50px;
background-color: #333;
color: #fff;
cursor: pointer;
}
JavaScript代码:
const menuBtn = document.querySelector('.menu-btn');
const menu = document.querySelector('.menu');
menuBtn.addEventListener('click', function() {
menu.classList.toggle('active');
});