首页 > 解决方案 > 如何删除此代码中的重复?

问题描述

我只是在调用一个函数highlightInput(this),它只是改变所选输入的颜色。我认为可能有更好的方法来避免重复。有任何想法吗?

HTML 文件

<div class="form-group">
    <label for="your_name">Your name:</label>
    <input type="text" class="form-control" name="your_name" onfocus="highlightInput(this);">
</div>
<div class="form-group">
    <label for="email">Email:</label>
    <input type="email" class="form-control" name="email"onfocus="highlightInput(this);">
</div>
<div class="form-group">
    <label for="title">Event title:</label>
    <input type="text" class="form-control" name="title"onfocus="highlightInput(this);">
</div>
<div class="form-group">
    <label for="location">Event location:</label>
    <input type="text" class="form-control" name="location"onfocus="highlightInput(this);">
</div>


highlightInput 的样子:

var Color = {
    inputColor:function (color, self){
        $(self).css('backgroundColor', color);
    }
}

function highlightInput(self){
    Color.inputColor('lightyellow', self);
    $(self).blur(function(){
        Color.inputColor('white', self);
    });
}

标签: javascriptjqueryhtml

解决方案


摆脱 jQuery 并使用 CSS 来完成。

input.form-control:focus {
 background-color: lightyellow;
}
<input type="text" class="form-control">


推荐阅读