search

Home  >  Q&A  >  body text

How to use CSS to change the background color of a paragraph after clicking a link in an HTML page

<p>Can I change the background color of a paragraph when I click a link on the page. </p> <blockquote> <pre class="brush:php;toolbar:false;"><a href="#p4">Jump to P4</a> <p id="p4">I am P4</p></pre> </blockquote> <p>What do I need to write in CSS to achieve this -</p> <blockquote> <p>p {Background color: yellow; }</p> </blockquote></p>
P粉311423594P粉311423594457 days ago554

reply all(1)I'll reply

  • P粉286046715

    P粉2860467152023-09-02 19:39:28

    You cannot change the properties of an element by clicking on another element, but you can do so through JavaScript. Just add the <script> tag at the end of your <body> tag and onclick on the <a> tag ()event:

    <body>
        <a href="#p4" onclick="changeColor()">跳转到P4</a>
        <p id="p4">我是P4</p>
    
        <script>
          function changeColor() {
          document.getElementById("p4").style.backgroundColor = "yellow";
          }
        </script>
    </body>

    reply
    0
  • Cancelreply