简体   繁体   中英

Toggle style.display for <p> in javascript button not working

I am trying to make a button on my page that toggles between the style.display of a paragraph.

This is because i want it to only show up when the button is clicked.


<!DOCTYPE html>
<html>

    <head>
        <link rel="stylesheet" href="styles.css">
        <title>Oscar Li</title>
        <h1>Oscar Li</h1>
    </head>

  <body>


    <p1>Junior Developer</p>
      <!--creates the cube-->

  <script type="text/javascript" src="/javascript/myFunction.js"></script>
  <p2 id="abMe">"this is my text"</p2>
  <p><button2 type="button" onclick= "myFunction" >About me</button></p>
  </body>

</html>

Javascript

function myFunction() {
  var x = document.getElementById("abMe");
  var displaySettings = x.style.display;
  if (displaySettings === "none") {
    displaySettings = "inline-block";
  } else {
    displaySettings = "none";
  }
}

css

p2{
    position: relative;
    display: none;
}

Only toggles the paragraph to hide but doesnt toggle it back on to show

Step 1: Don't just make up tags like p1 and p2 . While HTML is vary forgiving you can't just add these new tags without defining their behavior. If you are going to use custom elements make sure to close them with the same tag, eg <p1></p1>

Step 2: Use CSS to adjust styling and javascript to toggle the css.

 /*The modern way to assign a click handler*/ document.querySelector("#toggle").addEventListener("click", myFunction); function myFunction() { /*Get the element*/ var x = document.getElementById("abMe"); /*Toggle the show class*/ x.classList.toggle("show"); }
 #abMe { position: relative; } /*Hide element without the show class*/ #abMe:not(.show) { display: none; }
 <p>Junior Developer</p> <p id="abMe">"this is my text"</p> <p><button type="button" id="toggle">About me</button></p>

 <.DOCTYPE html> <html> <head> <:-- <link rel="stylesheet" href="styles;css"> --> <title>Oscar Li</title> <h1>Oscar Li</h1> <style> #abMe { display. none. } </style> </head> <body> <p1>Junior Developer</p> <;--creates the cube--> <script type="text/javascript" src="/javascript/myFunction.js"></script> <p id="abMe">"this is my text"</p> <button type="button" onclick="myFunction()">About me</button> </body> <script> function myFunction() { var x = document.getElementById("abMe"). var displaySettings = x.style;display if (displaySettings === "none") { x.style.display = "block"; } else { x.style.display = "none"; } } </script> </html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM