切换标签上的样式(主动/焦点)仅用于CSS的输入字段 [英] toggling styles on label (active/focus) for input field with css only

查看:108
本文介绍了切换标签上的样式(主动/焦点)仅用于CSS的输入字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

想知道是否有一种 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:

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>

和CSS:

And CSS:

.active{ color:red; }

编辑:我确实知道孩子和兄弟姐妹选择解决方法,但为纯粹的样式而重新布置干净的标记似乎是不正确的,所以如果有另一种纯粹的CSS方式,这个答案就会胜出!

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/

推荐答案

试试这种方式: - 在输入后放置标签并将其左移。并申请兄弟姐妹。

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

<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



CSS

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



Demo



这是一种破解邻接​​兄弟选择器的方法,因为它仅适用于以下元素,而不适用于前一个。 将在这个元素后面选择所有相邻的同胞。因此,如果您对每个输入部分都有不同的 .row ,请使用 +

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 +.

这篇关于切换标签上的样式(主动/焦点)仅用于CSS的输入字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆