search

Home  >  Q&A  >  body text

How to change the background color of a button on click/HTML

I made a button similar to "Read More" and when I press it, a text expands down. When the text expands, the button's background changes, and when I press the button again to close the text (e.g. "Read Less"), the button's background returns to its original state. How to implement this function

function myFunction() {
        var dots = document.getElementById("dots");
        var moreText = document.getElementById("more");
        var btnText = document.getElementsByClassName("skillBtn");
      
        if (dots.style.display === "none") {
          dots.style.display = "inline";
          btnText.innerHTML = "阅读更多";
          moreText.style.display = "none";
        } else {
          dots.style.display = "none";
          btnText.innerHTML = "阅读更少";
          moreText.style.display = "inline";
        }
      }
#more {display: none;}
<div align="center"><h1 id="skillsid" style="margin-top:10px ;"> 编程语言 <span id="dots"></span> </h1><span id="more">
    这里写了一些内容
    
    <div align="center"><a href="#skillsid"><button class="skillBtn" onclick="myFunction()" ></button></a></div>

P粉502608799P粉502608799488 days ago545

reply all(1)I'll reply

  • P粉348088995

    P粉3480889952023-09-08 19:23:31

    What you are trying to do is called accordion. There is no need to write in JS, because HTML already has <details> and <summary> to implement this function:

    #more {
      display: none;
    }
    <details>
      <summary>编程语言</summary>
      这里写了一些内容
    </details>

    reply
    0
  • Cancelreply