javascript - 通过单击 div 隐藏和显示文本

标签 javascript jquery html css onclick

我有一个关于事件 onclick 的问题。我在研究过程中发现了这段代码。我的问题是:即使在点击之前文本已经出现,是否可以隐藏文本直到我们点击实际按钮。是否有可能让多个 onclick 事件单独工作,也就是说只打开上面的文本?谢谢

<html>
 <head>
  <title>Show and hide div with JavaScript</title>
  <script>
     function showhide()
     {
           var div = document.getElementById("newpost");
    if (div.style.display !== "block") {
        div.style.display = "block";
    }
    else {
        div.style.display = "none";
    }
     }
  </script>
 </head>
 <body>
  <div id="newpost">
    <p>This div will be show and hide on button click</p>
  </div>
  <button id="button" onclick="showhide()">Click Me</button>
</body>
</html>

最佳答案

快乐编码:)

function showhide() {
  var div = document.getElementById("newpost");
  div.classList.toggle('hidden'); 
}
.hidden{
display : none;
}
<html>
 <head>
  <title>Show and hide div with JavaScript</title>
 
 </head>
 <body>
 <!--if you want  by default hidden then add class .hidden in new post -->
  <div id="newpost"  class="hidden">
    <p>This div will be show and hide on button click</p>
  </div>
  <button id="button" onclick="showhide()">Click Me</button>
</body>
</html>

关于javascript - 通过单击 div 隐藏和显示文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47655563/

相关文章:

jquery - 使用 jQuery 捕获值

html - 可点击的图像页脚,html

html - 解码 gzip Chrome 缓存

javascript - 如何使用 Angular 设置默认选项?

javascript - 如何创建与 Gmail 联系人管理器类似的行为

javascript - 在创建钩子(Hook)后更新 sailsjs 模型中的未定义

javascript - Typescript:如何使用私有(private)变量反序列化 JSON 对象?

两个 Date() 之间的 JavaScript 差异(以月为单位)

jquery - 如何从头到尾运行函数?

javascript - VueJS。切换子组件模态