Is there a CSS alternative to JS click, (as :hover

2019-09-21 11:26发布

问题:

Update: Thanks to explanations by Crowes and Boltclock below, I now have a clearer understanding that CSS pseudo-classes are explicitly stative (ie. describing an element's state in the present moment).

While there is a chronological dimension to javascript events, CSS pseudo-classes are, by contrast, either true in the present moment or false.

Consequently, unlike the javascript events they superficially resemble, CSS pseudo-classes do not (and cannot) refer back to the user's previous interactions with that element.

This makes my question largely redundant.


In 2017, it's a great surprise that while CSS has had :hover for decades it still lacks that pseudo-class's most obvious complement - :click.

I have searched Stackoverflow and in this Nov 2012 question:

Can I have an onclick effect in CSS?

The highest rated answer:

use :active

is not a very good substitute for onclick - if anything :active is actually a substitute for onmousedown.

The second highest rated answer -

use the checkbox hack

is not semantic (and... as hacks go, it feels pretty hacky).

So. Is there a minimum effort pure CSS replacement for javascript's onclick?

回答1:

Is there a minimum effort pure CSS replacement for javascript's onclick?

Yes, there is a straightforward way to implement onclick behaviour using CSS alone.

Two steps:

  1. Add tabindex="0" to the element which requires the onclick behaviour
  2. Use the :focus pseudo-element to activate the onclick behaviour

Example:

p {
width: 100px;
height: 100px;
margin: 0;
line-height: 100px;
font-size: 16px;
text-align:center;
color: rgb(255,255,255);
background-color: rgb(255,0,0);
font-weight: bold;
cursor: pointer;
transform: rotateY(0deg);
transition:
    width 1s ease-out,
    font-size 1s ease-out,
    line-height 2s ease-out,
    height 1s ease-out 1s,
    transform 1s ease-out 2s;
}

p::after {
content:' Me';
}

p:focus {
width: 300px;
height: 200px;
line-height: 200px;
font-size: 36px;
transform: rotateY(360deg);
}

p:focus::after {
content:' Elsewhere';
}
<p tabindex="0">Click</p>