我正在創建一個小的JavaScript函數來打開或關閉一個div元素,沒有jQuery,但只有一個小的JavaScript和CSS,它正在工作,但我想實現以下內容:
加載頁面時,div開始總是隱藏的(完成)
如果訪問者點擊& quot打開& quot-按鈕時,將顯示div和文本& quot打開& quot必須在此保存按鈕中更改為& quot關閉& quot依此類推,根據div是打開還是關閉,我們顯示文本:open或CLOSE(正在處理,需要幫助)
這是一個更新的代碼筆: https://codepen.io/familias/pen/WNYQeqQ
var LetsDoThis = document.querySelector("#toggle");
var LetsDoThat = document.querySelector("#content");
LetsDoThis.addEventListener("click", function() {
LetsDoThat.classList.toggle("hidden");
});
.hidden {
display: none;
}
<button id="toggle">OPEN</button>
<div id="content" class="hidden">
When the "OPEN" button is clicked, the text must change from OPEN to CLOSE, all depending if it is open or closed
</div>
看看這是否能解決問題:
var LetsDoThis = document.querySelector("#toggle");
var LetsDoThat = document.querySelector("#content");
LetsDoThis.addEventListener("click", function({ currentTarget }) {
// true if the class is added or false if it is removed
let isOpen = LetsDoThat.classList.toggle("hidden");
currentTarget.textContent = isOpen ? 'OPEN' : 'CLOSE'
});
.hidden {
display: none;
}
<button id="toggle">OPEN</button>
<div id="content" class="hidden">
When the "OPEN" button is clicked, the text must change from OPEN to CLOSE, all depending if it is open or closed
</div>
您可以通過檢查按鈕的文本來做到這一點:
var LetsDoThis = document.querySelector("#toggle");
var LetsDoThat = document.querySelector("#content");
LetsDoThis.addEventListener("click", function() {
LetsDoThat.classList.toggle("hidden");
(LetsDoThis.innerHTML == 'OPEN') ? LetsDoThis.innerHTML = 'CLOSED': LetsDoThis.innerHTML = 'OPEN';
});
.hidden {
display: none;
}
<button id="toggle">OPEN</button>
<div id="content" class="hidden">
When the "OPEN" button is clicked, the text must change from OPEN to CLOSE, all depending if it is open or closed
</div>
修改事件處理程序以包含按鈕,如下所示。
LetsDoThis.addEventListener("click", function() {
LetsDoThat.classList.toggle("hidden");
LetsDoThis.innerText = LetsDoThis.innerText === "OPEN" ? "CLOSE" : "OPEN";
});