click事件修改css_CSS Click事件



CSS Click Events

For the last few years, we’ve been witnessing the wonderful expansion of front-end languages especially HTML with the HTML5 specifications and CSS with the CSS Level 3 specifications.

在过去的几年中,我们见证了前端语言的惊人扩展,尤其是HTML5规范HTML和CSS Level 3规范CSS。

We can now do a lot of stuff we couldn’t have done without JavaScript or images before, like rounded corners, gradients, responsive layouts, grid stuff, transparency in colors, and so much more.


But one thing we’ve always been missing is the possibility to handle click events with CSS. Actually, some people think we shouldn’t have this option since interactions are more like a JavaScript kind of stuff. I understand the idea, but it always bothered me to have to use JavaScript for a very simple click event.

但是我们一直缺少的一件事就是可以使用CSS处理点击事件。 实际上,有些人认为我们不应该使用此选项,因为交互更像是JavaScript之类的东西。 我理解这个主意,但是它总是让我不得不为一个非常简单的click事件使用JavaScript。

Anyway, as of today, CSS doesn’t provide any official way to handle a click event in CSS. But there are some very interesting tricks that we can use to “detect” a click using CSS only, without a single line of JavaScript, and this is what we are going to talk about today.

无论如何,到目前为止,CSS还没有提供任何正式的方式来处理CSS中的click事件。 但是,我们可以使用一些非常有趣的技巧来仅使用CSS来“检测”点击,而无需使用一行JavaScript,这就是我们今天要讨论的内容。

免责声明 (Disclaimer)

This blog post is about showing the possibilities of CSS and some clever hacks. It’s clearly not for “real life” use cases. Please, consider the whole article as a playground for experimenting, not as a tutorial to handle click events on your website or application.

这篇博客文章旨在展示CSS的可能性和一些聪明的技巧。 显然,这不是针对“现实生活”的用例。 请把整篇文章当作实验的游乐场,而不是作为处理网站或应用程序上的点击事件的教程。

Plus, some of these techniques are not well supported by browsers, meaning it’s even more borderline; we intend to have some fun pushing the limits of CSS.

此外,浏览器还没有很好地支持其中的某些技术,这意味着边界更广。 我们打算从CSS的极限中获得一些乐趣。

复选框黑客 (Checkbox hack)

Aaaaah, the checkbox hack. What a thing my friends! I’m sure you’ve all heard about the checkbox hack before. It’s probably the most common way to handle a click event in CSS. It relies on, well, a checkbox.

啊,复选框黑客。 我的朋友真是太好了我确定您之前都听说过复选框黑客。 这可能是处理CSS中的click事件的最常用方法。 它依赖于一个复选框。

What’s cool about a checkbox is the fact that it’s binary. It’s either checked or not checked. There is no “half-way” checked. This is why the checkbox hack is a pretty reliable way to trigger a click event in CSS. Let’s make an example.

复选框最酷的是它是二进制的。 选中或未选中。 没有检查“中途”。 这就是为什么复选框hack是触发CSS中的click事件的可靠方法。 让我们举个例子。

怎么运行的 (How it works)



<input type="checkbox">
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>



.to-be-changed {
	color: black;

input[type=checkbox]:checked ~ .to-be-changed {
	color: red;

As you can see, it relies on the :checked pseudo-class and on the general sibling selector ~. Please note that it also works like a charm with the adjacent sibling selector +. Basically, it says “if the checkbox is checked, then the following elements with the .to-be-changed class will be red”.

如您所见,它依赖于:checked伪类和常规的同级选择器~ 。 请注意,它与相邻的同级选择器+一样也具有魅力。 基本上,它说“如果选中此复选框,则具有.to-be-changed类的以下元素将为红色”。

Okay, a checkbox isn’t very sexy, but you can totally make something nicer by hiding the checkbox and binding a label to it. Something like this maybe:

好的,复选框不是很性感,但是您可以通过隐藏该复选框并将其绑定标签来使整体变得更好。 可能是这样的:

<input type="checkbox" id="toggle">
<label for="toggle">Click me!</label>
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>

So we hide the checkbox and use the label to trigger the click event.


input[type=checkbox] {
	position: absolute;
	top: -9999px;
	left: -9999px;

label {
	display: block;
	background: #08C;
	padding: 5px;
	border: 1px solid rgba(0,0,0,.1);
	border-radius: 2px;
	color: white;
	font-weight: bold;

input[type=checkbox]:checked ~ .to-be-changed {
	color: red;

This way, you have some kind of button triggering the color change on the paragraph. Isn’t that cool? Re-clicking on the button is switching the color back to black of course.

这样,您就可以通过某种按钮触发段落的颜色更改。 那不是很酷吗? 当然,重新单击按钮会将颜色切换回黑色。

(Note that there are different possibilities for hiding the checkbox, the most obvious of all being display:none.)

(请注意,隐藏复选框有多种可能性,其中最明显的是display:none 。)

You can see a demo here: Checkbox hack demo

您可以在此处查看演示: Checkbox hack demo

优点缺点 (Pros & Cons)

  • Binary, checked or not checked

  • Clicking again gets you back to the first state (can also be a con if you consider having to click a second time is a pain)

  • Allows chained click events (if first checkbox clicked and second checkbox clicked then do something)

缺点 (Cons)
  • Elements have to share the same parent (siblings)

  • Requires some extra HTML (input, label, etc.)

  • Requires two workarounds to make it work on mobile browsers (please refer to further readings)


进一步阅读 (Further reading)

There are like a bazillion demos with the checkbox hack since it’s clearly the most common way to handle a click event with pure CSS. However, there are probably a few things you may want to read about it:

复选框骇客演示不胜枚举,因为它显然是使用纯CSS处理click事件的最常用方法。 但是,您可能需要了解以下几件事:

:target方式(The :target way)

There is another way, well known to “fake” a click event with CSS, using the :target pseudo-class. This pseudo-class is quite similar to the :hover one in the way that it matches only a specific scenario.

众所周知,还有另一种使用:target伪类通过CSS“伪造”点击事件的方法。 伪类与:hover类非常相似,因为它仅匹配特定的方案。

The special event for the :target pseudo-class depends on what we call a “fragment identifier”. To put it simple, this pseudo-class refers to a hashtag you can see sometimes at the end of the URL. So it matches when the hashtag and the ID of an element are the same.

:target伪类的特殊事件取决于我们所谓的“片段标识符”。 简而言之,该伪类引用的是您可能有时在URL末尾看到的主题标签。 因此,当主题标签和元素的ID相同时,它就匹配。

怎么运行的 (How it works)



<a href="#id">Click me!</a>
<p id="id" class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>



.to-be-changed {
	color: black;

.to-be-changed:target {
	color: red;

Basically, when clicking on the link (href="#id"), the URL changes and you go to the anchor #id in the page. In this very moment, the element having this id can be targeted with the :target pseudo-class.

基本上,单击链接( href="#id" )时,URL会更改,您将转到页面中的锚点#id 。 此时,可以使用:target伪类将具有此id的元素作为目标。

You can see a demo here: :target way demo

你可以在这里看到一个演示::target way demo

优点缺点 (Pros & Cons)

  • Very light CSS

  • Perfect for highlighting sections

  • Messes with the browser history

  • Makes a page jump (when reaching to the anchor)

  • Requires an anchor tag to trigger the hashtag or a URL hack

    需要锚标签来触发主题标签或URL hack
  • Can only affect one element (since IDs are unique)

  • No way of getting back to first state without another hashtag, a link, or a URL hack

    没有其他标签,链接或URL hack,就无法回到第一状态

The browser support isn’t great but honestly, it’s not that bad. All major browsers support it well except Internet Explorer 6 to 8. So starting from IE9, you’re good.

浏览器支持不是很好,但是说实话,还不是很糟糕。 除了Internet Explorer 6至8,所有主流浏览器都很好地支持它。因此,从IE9开始,您感觉很好。

进一步阅读 (Further reading)

:focus方式(The :focus way)

Let’s continue with another way using a pseudo-class; the :focus one this time. It’s pretty much the same idea, except, it doesn’t expect a URL change. It relies on the user’s focus on a particular element.

让我们继续使用伪类的另一种方法。 :focus这次。 几乎是相同的想法,只是它不希望URL发生变化。 它依赖于用户对特定元素的关注。

When you’re on a web page, you can press the tab key to navigate through various elements on the page. It’s particularly useful when filling forms, to go from one field to another without having to use the mouse. It’s also used by blind or visually impaired people to navigate through a site.

在网页上时,可以按Tab键浏览页面上的各种元素。 在填写表格时,无需使用鼠标即可从一个字段转到另一个字段,这特别有用。 盲人或视障人士也可以使用它来浏览网站。

What’s important to note is that some elements can be focused, like links, inputs and such, and some other can’t, like paragraphs, divisions, and plenty others. Actually they can, but you’ll need to add the tabindex attribute with a numeric value.

需要注意的重要一点是,某些元素可以集中化,例如链接,输入等,而另一些则不能集中化,例如段落,分隔等。 实际上它们可以,但是您需要添加带有数字值的tabindex属性。

怎么运行的 (How it works)



<span tabindex="0">Click me!</span>
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>



span:focus ~ .to-be-changed {
	color: red;

So, when you click on the span or reach it with the tab key, it becomes focused and matches the :focus pseudo-class. The adjacent sibling selector does the rest. Pretty easy, right? If you don’t want to mess with the tabindex for any reason, you can simply use a link with a # href. It will work like a charm as well.

因此,当您单击跨度或使用Tab键将其移至该跨度时,它将变得聚焦并匹配:focus伪类。 相邻的兄弟选择器负责其余的工作。 很简单,对不对? 如果您不想由于任何原因弄乱tabindex,可以只使用带有#href的链接。 它也将像魅力一样工作。

You can see a demo here: :focus way demo

你可以在这里看到一个演示::focus way demo

优点缺点 (Pros & Cons)

  • Very light CSS and HTML

  • Great for navigation or similar

  • Requires either a focusable element or the tabindex attribute

  • Matches only when the element is focused (which means clicking elsewhere will mess it up)


进一步阅读 (Further reading)

过渡黑客(Transition hack)

This is probably the most wicked way to handle a click event in CSS. Seriously guys, this is madness. This technique comes from Joel Besada and has always been one of my favorite CSS tricks.

这可能是处理CSS中的click事件的最邪恶的方式。 认真的家伙,这是疯狂。 该技术来自Joel Besada,一直是我最喜欢CSS技巧之一。

The idea is to store a CSS style in a CSS transition. Yeah, you read it right, a CSS transition. Actually, the idea is pretty simple. It relies on applying a pseudo-infinite delay to a change in order to prevent it to get back to the default value. It may sound complicated but it’s fairly easy, trust me. Please have a look at the code.

这个想法是在CSS过渡中存储CSS样式。 是的,您没看错CSS过渡。 实际上,这个想法很简单。 它依赖于对更改应用伪无限延迟,以防止其恢复为默认值。 听起来很复杂,但是相当容易,相信我。 请看一下代码。

怎么运行的 (How it works)



<span>Click me!</span>
<p class="to-be-changed">I'm going to be red! It's gonna be legen... Wait for it...</p>



.to-be-changed {
	transition: all 0s 9999999s;

span:active ~ .to-be-changed {
	transition: all 0s;
	color: red;

The idea behind the first declaration is to delay any change to approximately 116 days to make sure the changes will stay once they’ve been set. It is not infinite, but kind of, right?

第一个声明背后的想法是将任何更改推迟到大约116天,以确保更改一旦设置便会保留。 它不是无限的,而是一种,对吗?

But we don’t want to apply the changes 116 days after clicking, we want it to be set immediately! So the idea is to override the delay during the click (:active pseudo-class) to apply the changes. Then when the click will be released, the old transition property will kick back in, setting back the delay to 9999999s, preventing the changes to going back to the default state.

但我们不想在点击后116天应用更改,而是希望立即进行设置! 因此,其想法是覆盖单击( :active伪类)以应用更改期间的延迟。 然后,当释放单击时,旧的过渡属性将重新出现,将延迟重新设置为9999999s,以防止更改返回到默认状态。

You can see a demo here: Transition hack demo

您可以在此处看到一个演示: Transition hack demo

优点缺点 (Pros & Cons)

  • Insanely clever

  • Keeps the exact value when releasing the click, even if the transition isn’t finished yet (see below)


Like Joel Besada states:

就像乔尔·贝萨达(Joel Besada)所说:

[…] a cool fact is that you can end a transition halfway through and have the property still keep the exact value that it had at that point in the transition. So for example, let’s say we have a linear transition from opacity 1 to 0 over two seconds, but only let it run for one second. The opacity value should now be stuck at 0.5 because the delay prevents it from going back. If we now were to run the opacity transition again, it would continue from 0.5 instead of starting over from the beginning.

[…]一个很酷的事实是,您可以在过渡中途结束过渡,并让该属性仍然保留过渡时该点的确切值。 举例来说,假设我们在两秒钟内从不透明度1到0进行了线性转换,但只让其运行了一秒钟。 现在,不透明度值应保持在0.5,因为延迟会阻止它返回。 如果现在再次运行不透明度转换,它将从0.5开始而不是从头开始。

缺点 (Cons)
  • Decent but not so good browser support (not IE9- and Opera Mini)

    不错,但浏览器支持不太好(不是IE9和Opera Mini)
  • Only works with transitionable values

  • No way of getting back to the first state

  • Not really infinite if you can afford waiting 116 days


进一步阅读(Further reading)

You should definitely read the original article by Joel Besada:

您绝对应该阅读Joel Besada的原始文章:

最后的话 (Final words)

As of today, we can do some click detections with CSS. I mean, this is possible even if it’s pretty much a hack in any case. Some ways are better than others for some situations, but all in all, it’s not something to be used in a real project.

到目前为止,我们可以使用CSS进行一些点击检测。 我的意思是,即使在任何情况下都是骇客,这都是可能的。 在某些情况下,某些方法比其他方法要好,但总而言之,这不是在实际项目中使用的方法。

Tab Atkins Jr. blogged about this a few months ago. He wrote a whole proposal about toggling states in CSS. A glance at his work:

Tab Atkins Jr.几个月前就对此发表了博客。 他撰写了有关在CSS中切换状态的完整提案。 看一下他的工作:

toggle-states:  none | <integer> sticky? | infinity  (initial: none)
toggle-group:   none | <ident>  (initial: none)
toggle-share:   none | <selector>#  (initial: none)
toggle-initial: <integer>  (initial: 1)

… where:


  • toggle-states is the basic function that turns toggle functionality on/off. None means it doesn’t toggle, 2 or more implements different states of checked.

    toggle-states是打开/关闭切换功能的基本功能。 None表示不切换,2个或更多实现不同的checked状态。

  • toggle-group implements the radio-button functionality. If you click an element with toggle-group set to a non-none value, all elements sharing the same toggle-group will be automatically set to first state (off)

    toggle-group实现单选按钮功能。 如果单击切换组设置为非值的元素,则共享同一切换组的所有元素将自动设置为第一状态(关闭)

  • toggle-share implements the label functionality. When you click an element with toggle-share, it acts as if you’d clicked all the elements it points to.

    toggle-share实现标签功能。 当您单击带有切换共享的元素时,它的作用就像您单击了它所指向的所有元素。

  • toggle-initial sets the initial state of the toggle


However, he admitted his idea is not perfect and can still face some issues and paradoxes. I won’t go any further into the topic since it would be out of the scope of this article, but I highly suggest you read it. Even if it’s incomplete, it’s still brilliant.

但是,他承认自己的想法并不完美,仍然会遇到一些问题和悖论。 我不会进一步讨论该主题,因为它不在本文的讨论范围之内,但是我强烈建议您阅读它。 即使不完整,它仍然是出色的。

So we’re back to JavaScript. It’s probably the best way to go if you want consistency and reliability. However, if you want to have fun doing things “the pure CSS way”, then you might have found this article useful. 😉

现在我们回到JavaScript。 如果需要一致性和可靠性,这可能是最好的方法。 但是,如果您想以“纯CSS方式”做事有趣,那么您可能会发现本文很有用。 😉

On a side note, Chris Coyier at CSS-Tricks wrote a blog post about handling double clicks with pure CSS about 2 years ago. It may be old, but it’s still very interesting to see some of the ways to get (or fail to get) there.

附带说明一下,大约在2年前,CSS-Tricks的Chris Coyier撰写了一篇有关使用纯CSS处理双击的博客文章。 它可能很旧,但是看到一些到达(或失败)那里的方法仍然很有趣。

Anyway, thanks a lot for reading guys. Please be sure to ask questions or show any related work!

无论如何,非常感谢你们阅读。 请务必提出问题或显示任何相关工作!

Download all examples




评论将由博主筛选后显示,对所有人可见 | 还能输入1000个字符
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页