如何显示/隐藏内容

How to show/hide content

本文关键字:隐藏 显示 何显示      更新时间:2023-09-26

我有一个页面,我想要两个按钮,当一个按钮被点击时,会显示hello,当另一个被点击时会隐藏"hello"消息,然后显示"再见"。我知道这需要用javascript来完成,但我不擅长javascript。

检查这个片段

<p id="msg"></p>
<button onclick="helloFunction()">Say Hello</button>
<button onclick="byeFunction()">Wave Goodbye</button>
<script>
function helloFunction() {
    document.getElementById("msg").innerHTML = "Hello";
}
  
  function byeFunction() {
    document.getElementById("msg").innerHTML = "Goodbye";
}
</script>

有几种方法可以做到这一点,其中一种方法会影响打招呼或道别的dom元素的可见性,另一种方法如下所示,您实际上会根据按下哪个按钮来更改dom对象的文本

<button onClick="javascript:say('Hello');">Say Hi</button>
<button onClick="javascript:say('Goodbye');">Say Goodbye</button>
<div id="TextField"></div>
<script>
    function say(text) {
        var element = document.getElementById("TextField");
        element.innerHTML = text;
    }
</script>

这里是实现这一壮举所需要的。

首先创建一个div或p标记来保存ur文本和两个按钮例如

    <div id="container">Hello</div>
    <button id="show">Show</button>
    <button id="hide">Show</button>

确保你的div有一个id,你的按钮也有。你可以参考一下。

然后在javascript中,您可以切换div 的显示或可见性

   <script type="text/javascript">
      //Declare variable
     var div = document.getElementById("container");
     var show = document.getElementById("show");
      var hide = document.getElementById("hide");
     //run when windows fully loads
     window.onload = function(){
         //when i click show button
         show.onclick = function(){
                div.style.display = "block";
          }
         //when i click hide button
         hide.onclick = function(){
              div.style.display = "none";
            }
         }
      //That is champ, this is all vanilla javascript. You can also look              into implementing with jquery.
    </script>