Answer as of 2021:
The best way (actually the only way*) to simulate an actual click event using only CSS (rather than just hovering on an element or making an element active, where you don't have mouseUp) is to use the checkbox hack. It works by attaching a label
to an <input type="checkbox">
element via the label's for=""
attribute.
This feature has broad browser support (the :checked
pseudo-class is IE9+).
Apply the same value to an <input>
's ID attribute and an accompanying <label>
's for=""
attribute, and you can tell the browser to re-style the label on click with the :checked
pseudo-class, thanks to the fact that clicking a label will check and uncheck the "associated" <input type="checkbox">
.
* You can simulate a "selected" event via the :active
or :focus
pseudo-class in IE7+ (e.g. for a button that's normally 50px
wide, you can change its width while active
: #btnControl:active { width: 75px; }
), but those are not true "click" events. They are "live" the entire time the element is selected (such as by Tabbing with your keyboard), which is a little different from a true click event, which fires an action on - typically - mouseUp
.
Basic demo of the checkbox hack (the basic code structure for what you're asking):
label {
display: block;
background: lightgrey;
width: 100px;
height: 100px;
}
#demo:checked + label {
background: blue;
color: white;
}
<input type="checkbox" id="demo"/>
<label for="demo">I'm a square. Click me.</label>
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…