简体   繁体   中英

Button clicked display in the list of buttons using CSS only

I have 4 buttons in an HTML which is in list (ul > li) format. I want to implement a functionality where one of the buttons will be shown as clicked (clicked css style applied). Then on clicking any other button in the list, the already clicked button style should change and then only the newly clicked button should be shown as clicked (clicked css style applied). Thereby, other buttons will have unclicked style.

This can be handled using javascipt, but I'm specifically looking to achieve this with only css. I'm unable to solve this.

I'm new to CSS programming and hence requesting help in this regard.

Add a class to the clicked element after removing that class from all other elements. Use jquery addClass and removeClass methods.The only extend you can achieve using css with input tags is by using the pseudo class :focus (any click outside the button will remove the focus though.). Its not possible to keep the styles if you are going to click on anywhere outside the button.

 $(document).ready(function(){ $('input[type=button]').click(function(){ $('.active').removeClass('active'); $(this).addClass('active'); }); }); 
 .active{ background:white; border:1px solid red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <ul> <li> <input type="button" value="A"/> </li> <li> <input type="button" value="B"/> </li> <li> <input type="button" value="C"/> </li> <li> <input type="button" value="D"/> </li> </ul> 

If you want to avoid jquery then use selector.className (type string) or selector.classList (type array).

EDIT

If you are willing to use anchor instead of input tag then I've a pure css solution for you.

 a { display: block; border: 2px solid black; text-align: center; margin:5px; text-decoration:none; } a:active,a:target { border: 2px solid red; } 
 <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <meta charset="utf-8"> <title>JS Bin</title> </head> <body> <ul> <li> <a href="#a" id="a"/>a</a> </li> <li> <a href="#b" id="b"/>b</a> </li> <li> <a href="#c" id="c"/>c</a> </li> <li> <a href="#d" id="d"/>d</a> </li> </ul> </body> </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