css 自定义的JavaScript谷歌,改变字打开关闭或打开后点击

qojgxg4l  于 2023-06-25  发布在  Java
关注(0)|答案(3)|浏览(117)

我正在创建一个小的JavaScript函数来打开或关闭一个div元素,没有jQuery,只是一个小的JavaScript和CSS,它正在工作,但我想实现以下目标:
div开始时总是隐藏,加载页面(完成)
如果访问者点击“OPEN”按钮,则显示div,并且文本“OPEN”必须在此保存按钮中更改为“CLOSE”,依此类推,取决于div是打开还是关闭,我们显示文本:打开或关闭(正在处理并需要帮助)
下面是一个更新的Codepen与它: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>

我怎么能做到呢?

fnatzsnv

fnatzsnv1#

看看这是否修复了它:

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>
weylhg0b

weylhg0b2#

您可以通过检查按钮的文本来执行此操作:

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>
ogq8wdun

ogq8wdun3#

修改事件处理程序以包含按钮,如下所示。

LetsDoThis.addEventListener("click", function() {
  LetsDoThat.classList.toggle("hidden");
  LetsDoThis.innerText = LetsDoThis.innerText === "OPEN" ? "CLOSE" : "OPEN";
});

相关问题