最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Change the background color of an input element on focus - Stack Overflow

programmeradmin3浏览0评论

I would like to change the background colour of the text input (.item-input) when I press a tab key or via mouse - for some reason focus is not firing?

For example:

<tr class="item">
     <td> <input class="item-input" type="text" /> </td>
     <td> <input class="option" type="text" /> </td>
</tr>

If .item-input is selected via key or mouse

if($('.item-input').is(':focus')) {
    $(this).addClass("input-focus");
}

In the css file I have:

.input-focus {
    background-color: yellow;
}

I would like to change the background colour of the text input (.item-input) when I press a tab key or via mouse - for some reason focus is not firing?

For example:

<tr class="item">
     <td> <input class="item-input" type="text" /> </td>
     <td> <input class="option" type="text" /> </td>
</tr>

If .item-input is selected via key or mouse

if($('.item-input').is(':focus')) {
    $(this).addClass("input-focus");
}

In the css file I have:

.input-focus {
    background-color: yellow;
}
Share Improve this question edited Feb 8, 2015 at 0:38 Josh Crozier 242k56 gold badges400 silver badges313 bronze badges asked Feb 7, 2015 at 23:36 I'll-Be-BackI'll-Be-Back 10.8k42 gold badges118 silver badges227 bronze badges 1
  • Just use pure css developer.mozilla/en-US/docs/Web/CSS/:focus – epascarello Commented Feb 7, 2015 at 23:39
Add a ment  | 

1 Answer 1

Reset to default 5

Use plain CSS:

.item-input:focus {
  background-color: yellow;
}
<input class="item-input" type="text" />

But if you want to use jQuery, listen to the focus event:

$('.item-input').on('focus blur', function() {
  $(this).toggleClass("input-focus");
});
.input-focus {
    background-color: yellow;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input class="item-input" type="text" />

I replaced the .addClass() method with the .toggleClass() method under the impression that you want the class removed on blur.

发布评论

评论列表(0)

  1. 暂无评论