表单CSS:根据选中/未选中状态设置单选框的父级(标签)样式 [英] Form CSS: Styling a radio box's parent (label) based on checked / unchecked status
问题描述
所以我有一个表格。在表单中提出的大部分问题都是使用电台输入。
So i have a form. Most of the questions asked in the forms are using Radio inputs.
我要用
<label>Option1
<input type="radio">
</label>
<label>Option2
<input type="radio">
</label>
我使用:hover设置标签样式,给它一个微妙的背景变化,正在突出。但是,我希望所选选项的标签具有不同的彩色背景。有什么办法这样做使用CSS,或者我必须去用jQuery吗?
我想做的是为检查的输入框的父级(标签)声明样式。
I'm styling the Labels using :hover, giving it a subtle background change to indicate which option you are highlighting. However, i want the label for the selected option to have a different colored background. Is there any way of doing this using CSS, or do I have to go with jQuery? What i want to do is declare a style for the parent (label) of the checked input box.
进一步的头脑风暴我想更改父字段集的bkg-color在填充所有必填字段。我开始觉得jQuery是去这里的方式..?
Upon further brainstorming i'd like to change the parent fieldset's bkg-color upon having all required fields filled in. I'm starting to feel jQuery is the way to go here..?
[Notes:]
使用HTML5 / CSS3 / jQuery。
只能与Chrome或Firefox兼容。这是在笔记本电脑本地运行,只要它运行良好的计算机上,我不必担心在旧版浏览器上的兼容性等)。
[Notes:] Using HTML5 / CSS3 / jQuery. Only has to be compatible with Chrome or Firefox. This is something that is to run locally on a laptop, so as long as it runs fine on that computer I don't have to worry about compatibility on older browsers etc. :)
编辑:由Nick Carver发布的解决方案。几个补充,使这个工作正常与单选按钮。发布完整性:
Solution posted by Nick Carver. A few additions to get this to work properly with radio buttons. Posting for completeness:
$('input[type="radio"]').change(function() {
var tmp=$(this).attr('name');
$('input[name="'+tmp+'"]').parent("label").removeClass("checked");
$(this).parent("label").toggleClass("checked", this.selected);
});
$('input[type="checkbox"]').change(function() {
$(this).parent("label").toggleClass("checked", this.selected);
});
推荐答案
您的样式是父级,而不是子级。如果你在jQuery中做了,你会做类似的:
There isn't a way with pure CSS, since you're styling a parent and not a child. If you did it in jQuery you'd do something like:
$("fieldset :radio").change(function() {
$(this).closest("label").toggleClass("onClass", this.checked);
});
整体< fieldset>
样式取决于你的标记,如果你有一些类型的容器每个收音机设置在你可以检查如果没有一个:checked
元素内...如果他们都做,然后使用相同的 .toggleClass()
方法设置所有检查类打开或关闭。
The overall <fieldset>
styling would depend on your markup, if you have some sort of container each radio set is in you could check if none of those had a :checked
element within...if they all do, then use the same .toggleClass()
approach to set that "all checked" class on or off.
这篇关于表单CSS:根据选中/未选中状态设置单选框的父级(标签)样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!