为< label>设置样式根据其< input>的状态 [英] Style a <label> based on its <input>'s state

查看:59
本文介绍了为< label>设置样式根据其< input>的状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否只有CSS才能根据其输入状态来设置HTML标签的样式?

Is it possible, with only CSS, to style an HTML label dependent on its input's state?

就我而言,我想根据是否选中< input type ="checkbox"> 来设置样式.

In my case, I want to style an <input type="checkbox"> based on whether it's checked.

我尝试将标签放在输入中,但是Firefox和Chrome(至少)似乎将它们解析为同级,即使它们显然嵌套在输入源中也是如此.而且我不知道如何编写可以通过for =属性间接访问的CSS规则.

I tried putting the label inside the input, but Firefox and Chrome (at least) seems to parse them as siblings, even though they're clearly nested in the input source. And I don't know how to write a CSS rule that can indirect through a for= attribute.

我需要在此基础上编写Javascript吗?

Do I need to whip out the Javascript on this one?

推荐答案

它们不需要嵌套,这就是< label>中的"for"属性的含义.元素.

They don't need to be nested, that's what the "for" attribute is for in the <label> element.

在现代浏览器(支持CSS 2.1的浏览器)中,您可以使用同级选择器,例如

In modern browsers (those supporting CSS 2.1), you can use a sibling selector, such as

input + label {
  /* rules */
}

您必须将您的标记置于严格的同级关系中,例如:

You would have to have your markup in a strict sibling relationship, such as:

<input name="cb" id="cb" type="checkbox"><label for="cb">Checkbox</label>

这篇关于为&lt; label&gt;设置样式根据其&lt; input&gt;的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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