Affecting parent element of :focus'd element (

2019-01-14 20:10发布

问题:

This question already has an answer here:

  • Is there a CSS parent selector? 26 answers

How can I change the background of a parent <div> when an <input> or <a> is :focus'd (or any other dynamic pseudo-class?

Eg

<div id="formspace">
<form>
<label for="question">
How do I select #formspace for the case when a child is active?</label>
<input type="text" id="question" name="answer"/></form></div>

回答1:

Unfortunately css doesn't support parent selectors. :(
So the only way to do it is to use javascript like the jQuery parent method.

Update: CSS Selectors Level 4 will support parent selectors! http://www.w3.org/TR/selectors4/#subject



回答2:

The only way I can think of is with JavaSCript:

function focusLink(isOnFocus)
{
    if (isOnFocus)
      document.getElementById('formspace').className = "<make a focus class name here>";
    else
      document.getElementById('formspace').className = "<default class name here>";
}

...

<input onFocus="focusLink(true)" onBlur="focusLink(false)">

Hope that helps!