我想更改
<input type='button' class='button'>
当鼠标单击或按回车键时。
要在鼠标单击时更改颜色,我可以简单地使用以下css
.button:active{
background-color:#FFF;
}
对于输入键,我尝试了以下jQuery代码:
$('.button').keypress(function(e){
if(e.which == 13){
$(this).css('background-color','#FFF')
}
});
但这不起作用,现在点击返回后背景仍然是白色的。但是,我只希望在有人点击回车时背景变白。我怎样才能实现这一点?
使用按键/键键的组合来切换颜色:
$("button").keydown(function(e) {
// Sets the color when the key is down...
if(e.which === 13) {
$(this).css("background-color", "red");
}
});
$("button").keyup(function() {
// Removes the color when any key is lifted...
$(this).css("background-color", "");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>
Test
</button>
试试这个
.clicked{
background:#fff !important;
}
$('.button').keydown(function(e){
if(e.which == 13){
$(this).addClass('clicked');
}
e.preventDefault();
});
请尝试以下代码
$('.button').keypress(function(e){
if(e.which == 13){
$(this).css('background-color','#FFF');
}
});
$('.button').keyup(function(e){
if(e.which == 13){
$(this).css('background-color','');
}
});