我有一個類似于這里的下拉選單。我需要相同的行為,除了dropdown-content當用戶單擊任何項??目時該類應該隱藏。我正在為此尋找可能的 CSS 解決方案,這樣我就不必為此撰寫任何 JS。
我嘗試了不同的方法,但由于特殊性沒有得到我需要的行為。任何投入將不勝感激。
uj5u.com熱心網友回復:
你應該使用display: none. 或者用 JS 寫成這樣:
document.getElementById("dropdown-content-id").style.display = "none";
uj5u.com熱心網友回復:
只是為了添加 acharb07 所說的內容,只需在您的 HTML 檔案中添加一個腳本標記。雖然通常不喜歡在 HTML 中撰寫 JS,但在您的情況下,這似乎是正確的。你的代碼是
<script>document.getElementById("dropdown-content-id").style.display = "none";</script>
就那么簡單。
uj5u.com熱心網友回復:
focus-within這不是正確的方法,盡管您可以通過使用偽屬性來實作您想要的。
只需要添加以下樣式。
.dropdown-content:focus-within {
display:none !important;
}
檢查下面您作為示例提供的更新示例。
.dropbtn {
background-color: #04AA6D;
color: white;
padding: 16px;
font-size: 16px;
border: none;
}
.dropdown {
position: relative;
display: inline-block;
}
.dropdown-content {
display: none;
position: absolute;
background-color: #f1f1f1;
min-width: 160px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
}
.dropdown-content:focus-within {
display:none !important;
}
.dropdown-content a {
color: black;
padding: 12px 16px;
text-decoration: none;
display: block;
}
.dropdown-content a:hover {background-color: #ddd;}
.dropdown:hover .dropdown-content {display: block;}
.dropdown:hover .dropbtn {background-color: #3e8e41;}
<h2>Hoverable Dropdown</h2>
<p>Move the mouse over the button to open the dropdown menu.</p>
<div class="dropdown">
<button class="dropbtn">Dropdown</button>
<div class="dropdown-content">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/451922.html
