按键并运行函数 jquery

Press key and runs function jquery

当用户按退格键 (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%)";
    }
});

但是这段代码不起作用。

谢谢。

Try keydown instead of keypress.

$(document).keydown(function(e) {
    if(e.which == 8) { //-- or 13
        alert('8');
    }
});

See this

您使用的 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/

--90deg 更改为 -90deg ,--90deg 不是有效值。你可以使用 jQuery 设置背景

运行 代码段并在正文上按回车键,jquery v1.2.3 是代码段中最早可用的代码段我已经使用过它:

$("body").keypress(function(e) {
  if (e.which == 8 || e.which == 13) {

    $("body").css('background', '-moz-linear-gradient(-90deg, #004158 0%, #005472 100%)');
    $("body").css('background', '-webkit-linear-gradient(-90deg, #004158 0%, #005472 100%)');
    $("body").css('background', '-o-linear-gradient(-90deg, #004158 0%, #005472 100%)');
    $("body").css('background', 'linear-gradient(-90deg, #004158 0%, #005472 100%)');
  }

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script>