click事件修改css

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.

现在,我们可以做很多以前没有JavaScript或图像就无法完成的工作,例如圆角,渐变,响应式布局,网格内容,颜色透明性等等。

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)

The HTML

HTML


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

The CSS

CSS


.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.

因此,我们隐藏了该复选框,并使用标签来触发click事件。


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)

优点(Pros)
  • 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.)需要一些额外HTML(输入,标签等)
  • 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事件的最常用方法。 但是,您可能需要了解以下几件事:

  • The advanced checkbox hack (fixing both Android 4.1.2 and iOS 4/5 bugs) by Tim Pietrusky

    蒂姆·皮特鲁斯基(Tim Pietrusky )的高级复选框黑客(修复了Android 4.1.2和iOS 4/5错误)

  • Stuff you can do with the checkbox hack by Chris Coyier

    克里斯·科耶尔(Chris Coyier)的复选框骇客可以做的事情

  • Button switches with checkboxes by myself

    我自己的复选框带有按钮开关

: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)

The HTML

HTML


<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>

The CSS

CSS


.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)

优点(Pros)
  • Very light CSS很轻CSS
  • Perfect for highlighting sections非常适合突出显示部分
缺点(Cons)
  • 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)只能影响一个元素(因为ID是唯一的)
  • 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)

  • On :target by Chris Coyier

    开:克里斯·科耶尔的目标

  • What’s the deal with :target in CSS by Joshua Johnson

    Joshua Johnson如何处理CSS中的:target

  • Highlighting a section with :target by Jonathan Snook

    Jonathan Snook的:target突出显示了一个部分

  • Mimic a click event with CSS by Jeffrey Way

    用Jeffrey Way的CSS模仿点击事件

: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)

The HTML

HTML


<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>

The CSS

CSS


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)

优点(Pros)
  • Very light CSS and HTML非常轻巧CSS和HTML
  • Great for navigation or similar非常适合导航或类似
缺点(Cons)
  • Requires either a focusable element or the tabindex attribute需要焦点元素或tabindex属性
  • Matches only when the element is focused (which means clicking elsewhere will mess it up)仅在元素集中时匹配(这意味着单击其他位置会使其混乱)

进一步阅读 (Further reading)

  • Pure CSS clickable events by Ryan Collins

    Ryan Collins提供的纯CSS可点击事件

过渡黑客(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)

The HTML

HTML


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

The CSS

CSS


.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)

优点(Pros)
  • 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如果您负担得起等待116天,并不是真的无限

进一步阅读(Further reading)

You should definitely read the original article by Joel Besada:

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

  • Maintaining CSS style states using infinite transition delays by Joel Besada

    使用无限过渡延迟维护CSS样式状态,作者:Joel Besada

  • Moving a character on a gamepad with pure CSS by Joel Besada

    用纯CSS在游戏手柄上移动角色by 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

    toggle-initial设置toggle-initial的初始状态

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.

click事件修改css_CSS Click事件相关推荐

  1. Vue之@click、事件修饰符@click.stop与@click.prevent、按键修饰符@keyup.enter

    1.绑定监听@click: (以监听click为例,其他如keyup,用法类似)  v-on:click="fun"   @click="fun"   @cli ...

  2. web api、获取DOM元素的方式、事件理解、click事件在移动端300ms延时、事件对象、事件委托、常见事件类型

    web api: API(Application Programming Interface,应用程序编程接口)是一些预先定义的函数,目的是提供应用程序与开发人员基于某软件或硬件得以访问一组例程的能力 ...

  3. jquery click()方法模拟点击事件对a标签不生效的解决办法

    jquery click()方法模拟点击事件对a标签不生效的解决办法 参考文章: (1)jquery click()方法模拟点击事件对a标签不生效的解决办法 (2)https://www.cnblog ...

  4. js中的onclick事件和JQuery中的click方法以及on方法事件用法总结

    1.onclick是绑定的事件(它是一个事件),注意该事件绑定只是JacaScript中有(js中的),Jquery中并没有此事件,告诉浏览器在鼠标点击时候要做什么 2.click方法(jquery中 ...

  5. js(JavaScript):面向对象,Document对象:查找元素对象,修改元素,事件

    面向对象编程 面向对象的编程,那么是更符合人类所接触的世界的逻辑思维. 将一个系统划分为各个子系统,子系统又由各个模块构成,将每个模块,系统划分为一个个对象,给这些对象赋予某些角色(属性/功能/方法) ...

  6. echart移上去显示内容_echarts 使用formatter 修改鼠标悬浮事件信息操作

    formatter 一般用于格式化鼠标悬浮时间的信息,如果你的数据是JSON数组格式,那么不必和我这样一一判断扇形图的 ticket 值,使用 formatter 的 callback 时间即可自行对 ...

  7. Vue练习(修改为自定义事件)

    <template><div><!-- 添加增加方法 传递给子组件--><!-- 垃圾方法 --><!-- <Shijian :addTod ...

  8. echarts中formatter修改鼠标悬浮事件信息操作、echarts地图块、散点区分触发点击事件 只触发散点问题详解

    这里写目录标题 1.实例 2.案例详解 1.实例 这次我拿echarts中 地图组合散点图的实例 !!!实现效果:滑到散点显示不同于地图块的信息 及 formatter 提示窗自定义!!! 这个显示项 ...

  9. yapi 事件创建、修改等接口事件监听

    使用的yapi作为接口文档平台.出于业务需求需要对接口创建.修改.删除等事件进行监听. yapi已经实现并预留了这个口子,但是没有找到实现的文档.这里进行简单描述下使用的方式. 一.yapi创建.修改 ...

  10. wxml修改样式_微信小程序 动态绑定事件并实现事件修改样式

    微信小程序 动态绑定事件并实现事件修改样式 实例代码 wxml {{item.name}} js var reportTypeList = [ { name: "日报1", id: ...

最新文章

  1. BZOJ1598: [Usaco2008 Mar]牛跑步
  2. 关于团队建设,穆帅能教我们什么?
  3. python dict函数用法_如何将python中的dict作为参数传入c函数中用c做相关的处理?...
  4. Python Django 装饰器模式之二阶装饰器
  5. Windows安装Redis(转!)
  6. 报错curl: (7) Failed to connect to 127.0.0.1 port xxxx: Connection refused
  7. 【小窍门】浏览器兼容圆角Border-radius的问题
  8. 长春java培训老师
  9. 有关SQL Server 2008你一定要知道的八件事 之三
  10. 2020美赛回忆录|平生第一次打美赛的获奖方式......美赛准备方法和思想
  11. IDEA查看或修改JDK版本
  12. mysql批量导出工具_sql数据库批量导出|
  13. 【线性代数】P7 方阵的行列式伴随矩阵
  14. html表格冻结原理,html表格table冻结行和列
  15. 用python计算圆柱体积
  16. Unity喷墨效果Shader实现
  17. python,用pycharm写的评分系统
  18. BDCN:Bi-Directional Cascade Network for Perceptual Edge Detection论文解读和代码实现
  19. 形态学运用(去除图像噪点,提取水平线,垂直线)--OPenCV08
  20. python中的库有哪些餐厅_推荐一些实用的的 Python 库

热门文章

  1. 什么是ESAM安全模块
  2. DICOM 开源工具汇总
  3. 安鑫 十年资产翻十倍 普通人是怎么做到的
  4. 计算机系统更新从哪关闭,电脑总提示系统更新,怎么关闭?
  5. 聚类算法小结(1)——K均值聚类算法
  6. matlab 读取odb,求教用C++方式读取abaqus的odb数据中的问题!!!
  7. jlink 与 swd 接口定义
  8. 数据结构:图的深度优先遍历和广度优先遍历
  9. TFTLCD显示实验_STM32F1开发指南_第十八章
  10. prometheus实战(一) 原理介绍