今日已更新 412 条资讯 | 累计 19972 条内容
关于我们

The Shifting Line Between CSS States and JavaScript Events

Daniel Schwarz 2026年06月29日 21:03 2 次阅读 来源:CSS-Tricks

CSS has always had pseudo-classes that style things when baed on user interactions. Recent features, however, are blurring the line between what CSS "listens" for and how they are alternatives to what Javascript typically listens for. The Shifting Line Between CSS States and JavaScript Events originally handwritten and published with love on CSS-Tricks . You should really get the newsletter as well.

CSS is listening to us. No, not like that . Rather, CSS is accumulating more and more pseudo-classes to help us respond to JavaScript events so that we don’t have to do so with JavaScript itself. But while pseudo-classes track states, not events, they sure can feel like event listeners sometimes (not that it really matters in the context of CSS). Then again, what is CSS these days? For example, there’s a proposal for event-trigger in the Animation Triggers spec, which would basically listen for events and trigger animations. If you ask me though, the syntax is capable of a lot more than that (think: invoker commands but for CSS). But to stay in today’s reality, I’ll walk you through the different CSS pseudo-classes out there that are kind of like event listeners, before doing the same for event-trigger , where I’ll show you how (I think) this currently unsupported feature would work. “Event listening” pseudo-classes :hover and :active The :hover state captures the moment from when the pointerenter event fires to when the pointerleave event fires, which perfectly illustrates why pseudo-classes are states, not events. :active matches the target (e.g., a link or button) that’s currently being pressed with a mouse, finger, or stylus, which makes it akin to pointerdown and pointerup / pointercancel . By the way, the pointer-events: none CSS declaration prevents pointer events from firing on the selected element! :focus and :focus-visible The :focus pseudo-class is akin to the focus and blur (unfocus) JavaScript events, but :focus-visible is a bit more complex. :focus-visible triggers when :focus does, but in addition, the browser uses a variety of heuristics to determine whether or not a focus indicator should be shown. Is the user operating with a keyboard? Is the element a form control? This really makes me appreciate what CSS offers. In fact, the best way to handle this using JavaScript is to query the CSS pseudo-class: element.addEventListener("focus", (event) => { i
本文内容来源于互联网,版权归原作者所有
查看原文