根据按下的键更改图像大小

时间:2017-04-12 19:58:50

标签: jquery html keydown

    $(window).keydown(function(event){
    var c = String.fromCharCode(event.which);
    if (c === 'a'){
        myImage.css("height", "+=2");
        myImage.css("width", "+=2");
    } else if (c === 's'){
        myImage.css("height", "-=2");
        myImage.css("width", '-=2');
    }
});

这是我的代码,我试图在按下s键时使图像缩小2像素,按下a键时使图像大2像素。代码现在没有做任何事情。

我收到警告“不推荐使用getpreventdefault()”,但我不认为这是造成这种情况的原因。

编辑:我应该提到警告仅在按下某个键后出现。

1 个答案:

答案 0 :(得分:0)

只需计算每个按键的宽度和高度。更新宽度和高度。

$(window).keydown(function(e){
  var $img = $('#myImg'),
      key = e.which,
      height = $img.height(),
      width = $img.width();

  if (key === 65)
    $img.css("height", height + 2).css("width", height + 2);
  else if (key === 83)
    $img.css("height", height - 2).css("width", height - 2);
});

查看fiddle here的工作示例。如果您需要计算不同的密钥,则可以获得密钥代码from this sweet codepen