繁体   English   中英

jQuery更改输入焦点上的字段集背景颜色

[英]Jquery Change Fieldset Background Color on Input Focus

下面的代码显示了input集中时其父fieldset背景颜色的变化。 我希望该字段集保持该背景色,直到另一个字段集中的输入被聚焦为止。 以下概念适用,除非字段集包含多个输入,则在关注下一个输入时会重新启用更改。 有什么想法吗? 谢谢!

jQuery的

jQuery("input[title]").focus(function() {
    jQuery(this).closest('fieldset').animate({backgroundColor: "#7e7451", color: "#ffffff"}, 'slow');
});

jQuery("input[title]").blur(function() {    
    jQuery(this).closest('fieldset').animate({backgroundColor: "transparent", color: "#777777"}, 'slow');
});

HTML

<fieldset name="Fieldset 1" id="fieldset1">
    <legend>Fieldset 1</legend>
    <label for="input1"><strong>Input 1</strong>
        <input type="text" name="input1" id="input1" />
    </label>
    <label for="input2"><strong>Input 2</strong>
        <input type="text" name="input2" id="input2" />
    </label>
</fieldset>

<fieldset name="Fieldset 2" id="fieldset2">
    <legend>Fieldset 2</legend>
    <label for="input3"><strong>Input 3</strong>
        <input type="text" name="input3" id="input3" />
    </label>
    <label for="input4"><strong>Input 4</strong>
        <input type="text" name="input4" id="input4" />
    </label>
</fieldset>

etc

首先,由于您要设置背景色的动画,因此我假设您使用的是jQuery-UI。 这意味着如果您的javascript中的样式更改不明确,则应改为使用类来制作动画。

然后,为了能够执行您要执行的操作,需要将当前的“活动字段集”保存在变量中。 这样,只有在样式更改不再有效时,您才可以触发样式更改。

因此,您的CSS应该是这样的:

fieldset {
    background-color: transparent;
    color: #777;
}
fieldset.active {
    background-color: #7e7451;
    color: #FFF;
}

JavaScript将是

var activeFs = jQuery('#fieldset1'); // must be valid

jQuery("input")
    .focus(function() {
        var fs = jQuery(this).closest('fieldset');
        if (activeFs.attr('id') != fs.attr('id')) {
            activeFs.removeClass('active', 'slow');
            activeFs = fs;
        }
        fs.addClass('active', 'slow');
    }).blur(function() {
        var fs = jQuery(this).closest('fieldset');
        if (activeFs.attr('id') != fs.attr('id')) {
            fs.removeClass('active', 'slow');
        }
    });

注意:当您从一个输入转到另一个输入时,请注意两个事件会同时触发。 这意味着您无法在blur()上知道某个位置是否仍有焦点输入,因此此脚本将始终保持焦点集中的最后一个字段集处于活动状态。 但是,当用户单击其他位置或提交表单时,您当然可以轻松删除该active类。

如果您想使用代码,这是一个地方

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM