简体   繁体   English

更改焦点上输入元素的背景颜色

[英]Change the background color of an input element on focus

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? 我想在按Tab键或鼠标时更改文本输入( .item-input )的背景颜色-由于某种原因,焦点没有触发?

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 如果通过键或鼠标选择了.item-input

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

In the css file I have: 在css文件中,我有:

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

Use plain CSS: 使用纯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: 但是,如果要使用jQuery,请听focus事件:

 $('.item-input').on('focus blur', function() { $(this).toggleClass("input-focus"); }); 
 .input-focus { background-color: yellow; } 
 <script src="https://ajax.googleapis.com/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 . 我更换了.addClass()与方法.toggleClass()所需的类上取下的印象法blur

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

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