css checkbox hack 是如何工作的? [英] How does css checkbox hack work?

查看:21
本文介绍了css checkbox hack 是如何工作的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚遇到了仅使用 css 创建的开关切换按钮.它被称为复选框黑客.

I just came across the switch toggle button which is created only using css. It known as the checkbox hack.

对于那些不知道复选框 css hack 是什么的人,请在这里阅读

For those who doesn't know what a checkbox css hack is, Please read it here

https://css-tricks.com/the-checkbox-hack/

我试了一下,效果很好.但我不明白这是如何工作的,因为我们没有点击复选框.

I tried it out and it was working perfectly fine. But I didn't understand how this is working because we are not clicking on the checkbox.

所以我有两个问题

  1. 这是如何工作的?

  1. How is this working ?

我尝试使用 display: none; 而不是绝对定位它仍然有效.这种方法有什么缺点吗?

Instead of absolute positioning I tried it with display: none; It still worked. Does this method have any drawbacks?

推荐答案

它的工作方式是使用 元素.任何输入元素都可以(通常应该)有一个标签.您可以使用 for 属性告诉浏览器哪个标签属于哪个标签,参考输入的 name:

The way it works is by using the <label> element. Any input element can (and usually should) have a label. You can tell the browser which label belongs to which label by using a for attribute, referring to the input's name:

<input name="myName" />
<label for="myName">Label</label>

每当您点击标签时,它都会聚焦输入(或者在复选框的情况下,切换它).

Whenever you click the label, it focuses the input (or in case of checkboxes, toggles it).

标签和复选框不必彼此靠近.您可以在文档的开头或结尾添加一些隐藏的复选框,并将标签放置在页面上的任何位置,它们仍然会聚焦输入.

The label and checkbox don't have to be near each other. You could add a few hidden checkboxes at the start or end of a document and place the labels anywhere on the page, and they'd still focus the input.

通过 display: none 隐藏复选框可能会导致某些浏览器出现错误行为.仅通过 position: absolute 将其隐藏起来更安全.

Hiding the checkbox through display: none could cause buggy behavior on certain browsers. Just hiding it from view by a position: absolute is safer.

这篇关于css checkbox hack 是如何工作的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆