是否有CSS替代JS click(例如:hover是mouseover/mouseout的替代方法)? [英] Is there a CSS alternative to JS click, (as :hover is an alternative mouseover / mouseout)?
问题描述
更新:由于下面Crowes和Boltclock的解释,我现在更加清楚地了解CSS伪类是显式的 ststative (即,在现在).
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).
尽管javascript事件具有按时间顺序排列的维度,但相比之下,CSS伪类是当前为true 或 false .
While there is a chronological dimension to javascript events, CSS pseudo-classes are, by contrast, either true in the present moment or false.
因此,不同于它们表面上类似于javascript的事件,CSS伪类不会(也不能)回溯到用户以前与该元素的交互.
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.
2017年,令人惊讶的是,尽管CSS已有:hover
几十年了,但它仍然缺少伪类最明显的补语-:click
.
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
.
我搜索了Stackoverflow,并在2012年11月的这个问题中进行了搜索:
I have searched Stackoverflow and in this Nov 2012 question:
最高评分的答案:
使用
:active
不是onclick
的很好替代品-如果:active
实际上是onmousedown
的替代品.
is not a very good substitute for onclick
- if anything :active
is actually a substitute for onmousedown
.
评分第二高的答案-
使用复选框黑客
use the checkbox hack
不是语义的(而且...随着黑客的发展,它感觉很hacky).
is not semantic (and... as hacks go, it feels pretty hacky).
所以.
推荐答案
是否只需花费最少的精力即可用纯CSS替换javascript的
onclick
?
Is there a minimum effort pure CSS replacement for javascript's
onclick
?
是的,有一种直接使用CSS来实现onclick
行为的直接方法.
Yes, there is a straightforward way to implement onclick
behaviour using CSS alone.
两个步骤:
- 在需要
onclick
行为的元素中添加tabindex="0"
- 使用
:focus
伪元素激活onclick
行为
- Add
tabindex="0"
to the element which requires theonclick
behaviour - Use the
:focus
pseudo-element to activate theonclick
behaviour
示例:
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>
这篇关于是否有CSS替代JS click(例如:hover是mouseover/mouseout的替代方法)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!