Make LI have active state when input is focussed using css
Is there a way to make an <li>
have an active state when an input field is focussed using CSS only? If not, any suggestions on the best way to go about achieving this?
See live demo: http://jsfiddle.net/W5LzP/
In the example, I want the background colour of the LI
to stay yellow when the user clicks in the input field.
Example HTML:
<ol>
<li>
<label for="first_name">Your first name</label>
<input name="first_name" placeholder="Type Y开发者_如何学Goour First Name" /></li>
<li>
<label for="lastt_name">Your last name</label>
<input name="last_name" placeholder="Type Your Last Name" />
</li>
<li>
<label for="email_address">Your first name</label>
<input name="email_address" placeholder="Type Your Email Address" />
</li>
<li>
<label for="country">Your country</label>
<input name="country" placeholder="Select your country from the drop down list" />
</li>
</ol>
Example CSS:
ol li label{
display:block;
}
ol li{
margin-bottom:8px;
background-color:#CCC;
}
ol li:hover{
background-color:#090;
}
ol li:active{
background-color:#FF9;
}
ol li input:focus{
border:1px solid #99C;
background-color:#99F;
}
CSS can only select descendants, it can't select ancestors (perhaps it should for the reason you have outlined).
You would have to use JavaScript, look at parentNode property.
var inputs = document.getElementsByTagName('input');
for (var i = 0, inputsLength = inputs.length; i < inputsLength; i++) {
inputs[i].onfocus = function() {
this.parentNode.className += 'active';
}
inputs[i].onblur = function() {
this.parentNode.className = this.parentNode.className.replace(/\bactive\b/, '');
}
}
jsFiddle.
Unfortunately css doesn't support parent selectors. So the only way to do it is to use javascript like the jQuery parent method.
精彩评论