我有一个问题,使用CSS(尝试JS和它是一样的,它不工作)的一个菜单。当我点击我的按钮打开菜单,它立即出现,我如何才能使过渡顺利?
这是HTML代码:
<div class="sidenav">
<a href="#about">About</a>
<a href="#services">Services</a>
<a href="#clients">Clients</a>
<a href="#contact">Contact</a>
<button class="dropdown-btn">Dropdown
<div class="dropdown-arrow">▼
</div>
</button>
<div class="dropdown-container">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
<a href="#contact">Search</a>
</div>
字符串
CSS:
/* Style the sidenav links and the dropdown button */
.sidenav a, .dropdown-btn {
padding: 8px 0px 0px 0px;
display: block;
border: none;
background: none;
text-align: left;
color: #727272;
text-decoration: underline;
font-size: 16px;
line-height: 1.5;
cursor: pointer;
outline: none;
}
.dropdown-arrow {
padding-left: 2px;
display: inline-block;
font-size: 9px;
}
/* On mouse-over */
.sidenav a:hover, .dropdown-btn:hover {
color: #a0a0a0;
}
/* Dropdown container (hidden by default). */
.dropdown-container {
display: none;
padding-left: 16px;
}
型
和JS让出现的(它让出现下拉容器):
<script>
var dropdown = document.getElementsByClassName("dropdown-btn");
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function() {
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
}
});
}
</script>
型
首先,我尝试在.dropdown-container
内部的CSS中添加transition: height .4s ease;
行,什么都没有,它不起作用。然后我在JS代码中添加了相同的transition代码行,如下所示:
<script>
var dropdown = document.getElementsByClassName("dropdown-btn");
var container = document.getElementsByClassName("dropdown-container"); /*ADDED LINE THIS HERE*/
var i;
for (i = 0; i < dropdown.length; i++) {
dropdown[i].addEventListener("click", function() {
this.classList.toggle("active");
var dropdownContent = this.nextElementSibling;
if (dropdownContent.style.display === "block") {
dropdownContent.style.display = "none";
} else {
dropdownContent.style.display = "block";
container.style.transition = "transform 0.4s ease"; /*ADDED LINE THIS HERE*/
}
});
}
</script>
型
也尝试了transition: all 0.4s;
,但是all参数也不起作用。
2条答案
按热度按时间efzxgjgh1#
你不能转换
display
属性,也不能在固定值(比如零)和auto
之间转换height
属性。最简单的选择是转换opacity
属性以获得淡入淡出效果,或者转换max-height
属性以获得飞入效果。l0oc07j22#
显示风格很难给予过渡。请改变高度。这是有意义的。祝你好运。
个字符