Creating a toggle button that stays depressed when clicked is not directly achievable with pure CSS. To achieve this effect, a combination of HTML, CSS, and JavaScript is required.
Using HTML and CSS:
Consider using a checkbox as the underlying semantic element. Style it differently based on whether it's checked or not. However, this approach may involve additional HTML and CSS complexity.
Using jQuery:
A better solution is to employ jQuery. Here's a compact function that toggles a button's styling between two states:
<code class="js">$(document).ready(function() { $('a#button').click(function() { $(this).toggleClass("down"); }); });</code>
Associated CSS:
To style the toggle button, use the following CSS:
<code class="css">a { background: #ccc; cursor: pointer; border: solid 2px; padding: 5px; } a.down { background: #bbb; border-color: #777 #777 #eaeaea #eaeaea; }</code>
HTML:
Finally, include the jQuery library and use the following HTML snippet to implement the button:
<code class="html"><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a id="button" title="button">Press Me</a></code>
The above is the detailed content of How to Create a Depressed Toggle Button with CSS and JavaScript?. For more information, please follow other related articles on the PHP Chinese website!