這個問題在這里已經有了答案: 不能使用變數來更改 css 屬性 3 個回答 3 小時前關閉。
我正在嘗試做一些事情,點擊一個 div 會在塊和無之間切換另一個 div 的顯示。
<div id="filtertop" onclick="toggleFilter()">Filter</div>
function toggleFilter() {
let x = document.getElementById("filter").style.display;
if (x == "none") {
x = "flex";
}
else{
x = "none";
}
}
目前,當我點擊 id="filtertop" 的 div 時,代碼什么也不做;顯示應該更改為無。
uj5u.com熱心網友回復:
@CherryDT 已經在評論中解釋了您的代碼問題。
您必須將 JS 更改為:
function toggleFilter() {
let x = document.getElementById("filter");
if (x == "none") {
x.style.display = "flex";
} else {
x.style.display = "none";
}
}
更智能、更現代的解決方案是使用classList.toggle('class-name')以下示例所示的方法。這應用了一個 CSS 類并切換。因此,您不需要使用 if / else 陳述句。
function toggleFilter() {
document.querySelector('.filter').classList.toggle('d-none');
}
.filter {
display: flex;
}
.d-none {
display: none;
}
/* for styling purpose only */
.filter {
height: 50vh;
background-color: red;
grow: 1;
margin-top: 20px;
}
#filtertop {
font-size: 2em;
}
<div id="filtertop" onclick="toggleFilter()">Filter</div>
<div class="filter">Filter Element</div>
uj5u.com熱心網友回復:
你是那個意思?
function toggleFilter() {
let x = document.getElementById("filter");
if (x.style.display == "none") {
x.style.display = "flex";
} else {
x.style.display = "none";
}
}
<div id="filtertop" onclick="toggleFilter()">Filter</div>
<div id="filter">div with ID</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/343830.html
標籤:javascript html css 弹性盒
下一篇:函式沒有回傳正確的狀態
