javascript - 按下键并运行 jquery 函数

标签 javascript jquery function key

当用户按退格键 (8) 或回车键 (13) 时,我不会运行此函数。

$(document).keypress(function(e) {
    if(e.which == 8) { //-- or 13
        var x = document.getElementsByTagName("BODY")[0];
        x.style.backgroundImage = "-moz-linear-gradient(--90deg, #004158 0%, #005472 100%)";
        x.style.backgroundImage = "-webkit-linear-gradient(--90deg, #004158 0%, #005472 100%)";
        x.style.backgroundImage = "-o-linear-gradient(--90deg, #004158 0%, #005472 100%)";
        x.style.backgroundImage = "linear-gradient(-180deg, #004158 0%, #005472 100%)";
    }
});

但是这段代码不起作用。

谢谢。

最佳答案

你使用什么版本的 jQuery?

$(document).on('keypress', function(e) {
if(e.which == 8 || e.which == 13) { //-- or 13
    var x = document.getElementsByTagName("BODY")[0];
    x.style.backgroundImage = "-moz-linear-gradient(--90deg, #004158 0%, #005472 100%)";
    x.style.backgroundImage = "-webkit-linear-gradient(--90deg, #004158 0%, #005472 100%)";
    x.style.backgroundImage = "-o-linear-gradient(--90deg, #004158 0%, #005472 100%)";
    x.style.backgroundImage = "linear-gradient(-180deg, #004158 0%, #005472 100%)";
     e.preventDefault();
}
});

http://jsfiddle.net/pmq0215r/

关于javascript - 按下键并运行 jquery 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31228786/

相关文章:

php - jquery 动态添加行有问题

javascript - 设置多个文件上传的验证

javascript - ng-重复 : Limit to 10 most recent with exceptions

javascript - 如何使用 JQuery 获取 GET 和 POST 变量?

c++ - 将 Direct3D C++ 函数转换为 Delphi

javascript - jQuery 数据表 columnDefs 问题

c# - 在 asp.net C# 中获取禁用单选按钮控件的值

ajax - jQuery:通过ajax获取下一页并附加动画

r - 数据框中跨列的最大组合总和

python - Python 脚本中函数的顺序是否重要?