Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
525 views
in Technique[技术] by (71.8m points)

html - toggling styles on label (active/focus) for input field with css only

Wondering whether if there is a css-only way to perform to toggle styles on the corresponding label on input's focus. So far I have:

    $(document).on('focus active', 'input',function(){
        $('label[for='+$(this).attr('id')+']').addClass('active');
    });
    $(document).on('blur', 'input',function(){
        $('label[for='+$(this).attr('id')+']').removeClass('active');
    });

HTML:

    <div class="row">
     <label for="contact_form_mail">Email</label>
     <input id="contact_form_mail" name="contact_form_mail" type="email" placeholder="Your e-mail address...">
    </div>

And CSS:

.active{ color:red; }

Edit: I am surely aware of the child and sibling selectors "workarounds", but rearranging clean markup for the pure sake of styling seems not right, so if there is another pure css way this answer wins!

http://jsfiddle.net/fchWj/3/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Try this way:- Place your label after input and float it left. And apply siblings.

Html

<div class="row">
    <input id="contact_form_mail" name="contact_form_mail" type="email" placeholder="Your e-mail address...">
    <label for="contact_form_mail">Email</label>
</div>

CSS

label {
    float:left;
}
input:focus + label {
    color:red;
}

Demo

This is a hack to get the adjacent sibling selector work as it applies only on the following element and not the preceding one. ~ will select all the adjascent siblings after this element. So if you are having different .row for each section of inputs then use +.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...