Is there a CSS alternative to JS click, (as :hover is an alternative mouseover / mouseout)?

狂风中的少年 提交于 2019-12-13 09:25:44

问题


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>


来源:https://stackoverflow.com/questions/42070945/is-there-a-css-alternative-to-js-click-as-hover-is-an-alternative-mouseover

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!