如何在键盘“输入"按下时触发 :active 伪类?(仅使用 CSS) [英] How to trigger the :active pseudoclass on keyboard 'enter' press? (using only CSS)
问题描述
CSS:
a:focus { opacity: .75 }
a:active { transform: translateY(4px) }
意图:
键盘用户标签到链接,使用
:focus
样式作为视觉提示
他们点击enter
来激活链接;:active
样式提供视觉按键反馈
They hit enter
to activate the link; the :active
style gives visual keypress feedback
问题:
:active
样式可以正确触发鼠标点击,但不能正确触发按键.我可以只用 CSS 来解决这个问题吗?
The :active
style triggers properly for a mouse click, but not a keypress. Can I fix this with just CSS?
推荐答案
好问题!
是的,你不能再这样做了.
Yeah, you can't do this anymore.
很久以前,MSIE 像对待 :focus
一样对待 :active
,所以有一种方法可以通过超链接来实现这一点(这是在千兆互联网速度之前和浏览器除了愚蠢的挥舞旗帜或其他东西外,没有很好地显示正在进行的加载).
A long time ago MSIE treated :active
like :focus
so there was sort of a way to accomplish this with hyperlinks (this was before gigabit internet speeds and when browsers didn't do a good job of showing load-in-progress except for a dumb waving flag or something).
运行以下代码段以查看实际行为:
Run the below Snippet to see the behavior in action:
input type='button'
可以用ENTER
或SPACE
激活- 在按钮上按住
SPACE
将显示:active
样式(FireFox 除外;这看起来像 FF 错误,因为它适用于 mousedown) - 在按钮上按住
ENTER
会在每次键盘发送字符时重复触发onclick
. - 在按钮上按住
SPACE
会触发onclick
仅当SPACE
键被释放时仍聚焦在按钮上.(例如,您可以通过这种方式模拟鼠标单击:Tab 键到一个按钮,按住空格,然后再次击中 Tab 并释放它以取消单击.) - 只能使用
ENTER
激活超链接. - 点击超链接将显示
:active
样式,使用ENTER
(或触摸)不会.
input type='button'
can be activated withENTER
orSPACE
- Holding down
SPACE
on a button will show the:active
style (except for FireFox; this looks like FF bug since it works OK for mousedown) - Holding down
ENTER
on a button will repeatedly triggeronclick
every time your keyboard sends the character. - Holding down
SPACE
on a button will triggeronclick
only if theSPACE
key is released while still focused on the button. (For example, you can simulate mouse click this way: tab to a button, hold down space, then hit tab again and release it to cancel the click.) - Hyperlinks can be activated with
ENTER
only. - Clicking on hyperlinks will show
:active
style, usingENTER
(or touch) will not.
document.getElementById('t1').focus(); // set focus for easier demo
:active
{
color: Red;
}
<input type='text' id='t1' value='Set focus and hit tab'/>
<a href='javascript:;' onclick='console.log("Hyperlink")'>Hyperlink</a>
<input type='button' value='Button' onclick='console.log("Button")'/>
因此,您不得不为此使用 JavaScript 或 Flash/Silverlight 等插件.
So you are stuck using JavaScript or a plugin like Flash / Silverlight for this.
这篇关于如何在键盘“输入"按下时触发 :active 伪类?(仅使用 CSS)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!