javascript - jQuery KeyUp() 问题

标签 javascript jquery html css dom

一旦用户按下“a”,按钮颜色就会改变,然后一旦用户释放“a”按钮,它应该再次改变。按钮只有在按下字母“a”后才会改变颜色,松开时不会。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>website</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
    $(document).keyup(function(event) {
        if ( event.which == 97){
            $('.button0 input').css('color', 'rgb(0, 0, 255)');
        }
    });
    $(document).keypress(function(event) {
        if ( event.which == 97){
            $('.button0 input').css('color', 'rgb(128, 0, 0)');
        }
    });
});
</script>
<style type="text/css">
.button0 input{
    position:fixed;
    left:41px;
    top:12px;
    font-family:Arial;
    font-size:8px;
    font-weight:normal;
}
</style>
<body>
    <div class="button0">
        <input type="button" style="width: 303px;height: 165px;" value="Button"/>
    </div>
</body>
</html>

最佳答案

来自jQuery API page对于 .keypress():

Note that keydown and keyup provide a code indicating which key is pressed, while keypress indicates which character was entered. For example, a lowercase "a" will be reported as 65 by keydown and keyup, but as 97 by keypress. An uppercase "A" is reported as 65 by all events. Because of this distinction, when catching special keystrokes such as arrow keys, .keydown() or .keyup() is a better choice.

因此,您需要在 keyup 处理程序中将 event.which == 97 更改为 event.which == 65

关于javascript - jQuery KeyUp() 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8964390/

相关文章:

javascript - 如何处理来自其他网站的 "semi-image"URL ("images"的放置事件)

javascript - 用css3实现Windows 8 Tile "Click"动画

jQuery 标签或徽章文档

css - 背景图像的 div 定位

javascript - 在 VueJS 中使用列表渲染时如何对列表进行排序

javascript - 无法将 JSON 值分配给 JS 变量

javascript - 如何在 JavaScript 中使用 for 循环检索多个 JSON 对象

javascript - 如果选中该复选框,如何在该复选框旁边的文本中插入一行?

javascript - 历史记录恢复后,Knockout 绑定(bind)将解除绑定(bind)

html - 动态插入以前仅使用 HTML/CSS 使用的文本?