【问题标题】:Jquery Change Fieldset Background Color on Input FocusJquery在输入焦点上更改字段集背景颜色
【发布时间】:2014-04-02 16:55:50
【问题描述】:

下面的代码显示当 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

【问题讨论】:

    标签: javascript jquery input focus fieldset


    【解决方案1】:

    首先,由于您正在为背景颜色设置动画,因此我假设您使用 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 类。

    如果你想玩弄代码,这里是FIDDLE

    【讨论】:

    • 哇——完美!谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-05
    • 1970-01-01
    • 2015-02-12
    • 2020-08-01
    相关资源
    最近更新 更多