是否可以在输入上更改字段集的背景颜色:焦点?

时间:2011-12-29 00:32:32

标签: css fieldset

当光标位于该字段集的任何文本字段内时,是否可以更改窗体的字段集的背景颜色?

我认为这可能有效,但事实并非如此:

fieldset {background: #ffe;}
input[type=text]:focus+fieldset {background: #ff0;}

5 个答案:

答案 0 :(得分:8)

您无法根据其中一个孩子fieldset的焦点状态设置input的样式。

但是,您可以通过添加空div作为fieldset的最后一个子项并对其进行样式化来模拟效果。然后可以使用焦点div上的常规同级选择器更改此input的样式:

fieldset {
  border: none;
  position: relative;
  margin-bottom: 0.5em;
}

legend {
  position: relative;
  background: white;
}

input:focus {
  background: lightyellow;
}

input:focus ~ div {
  border: 2px solid black;
  background: #def;
}

fieldset > div {
  height: calc(100% - 0.5em);
  width: 100%;
  position: absolute;
  top: 0.5em;
  left: 0;
  border: 2px solid lightgray;
  z-index: -1;
}
<fieldset>
  <legend>Fieldset 1</legend>
  <input name="text1" type="text" />
  <input name="text2" type="text" />
  <div></div>
</fieldset>
<fieldset>
  <legend>Fieldset 2</legend>
  <input name="text3" type="text" />
  <input name="text4" type="text" />
  <div></div>
</fieldset>

答案 1 :(得分:1)

我担心CSS不可能,因为CSS没有一个选择器可以根据元素的子元素进行选择。您尝试中的选择器input[type=text]:focus+fieldset会匹配一个fieldset元素,该元素会立即跟随一个焦点文本输入框 - 这与您想要的完全不同。

然而,使用JavaScript处理此问题是可能且相当容易的。你只需要在fieldset中的字段上使用onfocus和onblur事件处理程序,这些处理程序可以为所有这些处理程序提供相同的功能。他们只会更改style.background元素的fieldset属性,

答案 2 :(得分:1)

现在可以使用:focus-within

  

焦点在CSS伪类中表示已获得焦点或包含已获得焦点的元素的元素。换句话说,它表示一个元素,它本身与:focus伪类匹配,或者有一个与:focus匹配的后代。 (这包括阴影树中的后代。)

     

MDN

fieldset {
  background: green;
  margin: 1em;
}

fieldset:focus-within {
  background: red;
}
<fieldset>
  <input>
</fieldset>

答案 3 :(得分:0)

如果由于可访问性原因而未使用fieldset,那么只需执行以下操作:

http://www.pmob.co.uk/temp/categorybox.htm

如果您需要边框和辅助功能,请考虑将字段集包装在div中,然后设置包含div而不是字段集的样式。

希望这有帮助!

马特

答案 4 :(得分:0)

如果你正在使用Jquery,并且你没有嵌套你的fieldsets,你可以做一个简单的绑定,它将自己附加到一个fieldsets中的所有页面控件,每当你关注/不关注任何这些控件时,一个类就是在包含控件的字段集中添加/删除。

以下是一个示例:

$('input, label, select, option, button', 'fieldset').each(function (index, item) { $(this).focus(function () { $(this).closest('fieldset').addClass('fieldsetFocus'); }); $(this).blur(function () { $(this).closest('fieldset').removeClass('fieldsetFocus'); }); });

相关问题