CSS Checkbox hack如何工作? [英] How does css checkbox hack work?

查看:60
本文介绍了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.

所以我有2个问题

  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?

推荐答案

其工作方式是使用<label>元素.任何输入元素都可以(通常应该)带有标签.您可以使用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天全站免登陆