简体   繁体   中英

How to change background colour dynamically using Css

I've set up a method which when a button is clicked changes it's background colour and resets the colour of the other three buttons. The method for button1 looks like this

<script>
    function changeBttn1() {
        document.getElementById("bttn1").style.backgroundColor = '#add8e6';
        document.getElementById("bttn2").style.backgroundColor = '#D3D3D3';
        document.getElementById("bttn3").style.backgroundColor = '#D3D3D3';
        document.getElementById("bttn4").style.backgroundColor = '#D3D3D3';
    }...

Also I want to be able to make the Div that applies to each button appear and the others hidden with the same button press. The Div uses Class=Collapse which corresponds to Display:None in Bootstrap.css but I want to change it to run from the same method as the buttons. How can I do both events using Css?

Please do it like this very simple and easy

 $('.my-btn').on('click',function(){ var colorval=$(this).attr('color'); $('.my-btn').css('background-color', 'grey'); $(this).css('background-color', colorval); }); 
 button{ background-color:grey; padding:10px; border:1px solid #000000; color:#ffffff; } 
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="button-wrapper"> <button class="my-btn" color="red">Red</button> <button class="my-btn" color="green">Green</button> <button class="my-btn" color="purple">Purple</button> </div> 

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