我知道我可以在聚焦的输入元素上设置一个样式,如下所示:
input:focus
{
background-color:yellow;
}
Run Code Online (Sandbox Code Playgroud)
但是,当输入具有焦点时,是否可以在父元素上设置样式?例如
<div class="foo">
<input type="text />
Hello
</div>
Run Code Online (Sandbox Code Playgroud)
输入有焦点时,我可以影响"foo"样式吗?
编辑:影响父元素的可能重复:focus'd元素(纯CSS + HTML首选)
但是,有人可以解释这是如何工作的吗?
css(还)中没有父选择器.http://css-tricks.com/parent-selectors-in-css/
但是,您可以使用jQuery选择它:
HTML
<div class="parent">
<input type="text" />
</div>
Run Code Online (Sandbox Code Playgroud)
CSS
.parent {
/* parent styles */
}
.parent.active {
/* do stuff when the input is hovered */
}
Run Code Online (Sandbox Code Playgroud)
JS
// listen for a focus event on the input,
// and then add a class to the parent
$('input').on('focus', function () {
$(this).parent().addClass('active');
});
Run Code Online (Sandbox Code Playgroud)