我不知道如何爲打開和關閉添加動畫。我知道這個腳本不太好,但是我沒有發現任何其他的菜單腳本,當點擊被丟棄的塊之外時,可能會自動關閉。謝謝。下面是代碼在Javascript中動畫div的外觀
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function myFunction() {
document.getElementById("myDropdown").classList.toggle("show");
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.dropbtn')) {
var dropdowns = document.getElementsByClassName("dropdown-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
.dropbtn {
background-color: #4CAF50;
color: white;
padding: 16px;
font-size: 16px;
border: none;
cursor: pointer;
}
.dropbtn:hover,
.dropbtn:focus {
background-color: #3e8e41;
}
.dropdown {
float: right;
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f9f9f9;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0, 0, 0, 0.2);
right: 0;
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
-ms-transition: all 0.3s;
-o-transition: all 0.3s;
transition: all 0.3s;
max-height: 0;
overflow: hidden;
opacity: 0;
-webkit-animation-duration: 0.55s;
animation-duration: 0.55s;
-webkit-animation-timing-function: ease;
animation-timing-function: ease;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown a:hover {
background-color: #f1f1f1
}
.show {
display: block;
max-height: 200px;
opacity: 1;
}
<div class="dropdown">
<button onclick="myFunction()" class="dropbtn">Dropdown</button>
<div id="myDropdown" class="dropdown-content">
<a href="#home">Home</a>
<a href="#about">About</a>
<a href="#contact">Contact</a>
</div>
</div>
你能澄清嗎?在菜單外點擊時,子菜單正在關閉。那是你追求的功能,不是嗎? –
你想要發生什麼樣的動畫?向上/向下滑動?淡入/淡出? –
如果您在'.dropdown-content'中刪除了'display:none;',它將起作用 – Brewal