当我按下 Tab 键或通过鼠标时,我想更改文本输入 (.item-input
) 的背景颜色 - 由于某种原因焦点未触发?
例如:
<tr class="item">
<td> <input class="item-input" type="text" /> </td>
<td> <input class="option" type="text" /> </td>
</tr>
如果通过按键或鼠标选择.item-input
if($('.item-input').is(':focus')) {
$(this).addClass("input-focus");
}
在我的CSS文件中:
.input-focus {
background-color: yellow;
}
最佳答案
使用纯 CSS:
.item-input:focus {
background-color: yellow;
}
<input class="item-input" type="text" />
但是如果你想使用 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" />
我将 .addClass()
方法替换为 .toggleClass()
方法,因为您希望在 blur
上删除该类.
关于javascript - 更改焦点输入元素的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28388810/