简体   繁体   English

用jQuery按下键时显示图像

[英]Show image when key is pressed with jQuery

im trying to make a simple app that when a key is pressed on the users keyboard an image appears respective to that letter. 我试图制作一个简单的应用程序,即在用户键盘上按下键时,该字母对应的图像就会出现。 I would like to do this for the entire alphabet (a, b, c...) 我想对整个字母(a,b,c ...)执行此操作

if a is pressed a.jpg shows up on my page, if r was pressed r.jpg would appear and so on. 如果按a,则a.jpg出现在我的页面上,如果按r,则r.jpg会出现,依此类推。

I was going to do this with a mega list of if else statements only im sure there must be another way? 我打算用大量的if else语句列表来执行此操作,但只能确保肯定还有另一种方法?

var ctrlPressed = false;
$(window).keydown(function(evt) {
  if (evt.which == 17) { // ctrl
    ctrlPressed = true;
      alert('sdf');
  }
})

This is how I would go about doing this: 这就是我要做的事情:

var letters = "abcdefghijklmnopqrstuvwxyz";
letters = letters.split("");
//I'm lazy; you should define an array of letters

$(window).keydown(function(e){
    key = e.which - 65; //makes a-z = 1-27
    key = letters[key];
    $('img[src="' + key + '.jpg"]').show();
}

Here is a working jsFiddle 这是一个工作的jsFiddle

Source(s) 来源(S)

jQuery API - keydown jQuery API-按键
jQuery API - Attribute Equals Selector jQuery API-属性等于选择器
MDN - String.split MDN-String.split

How about an array of image references where the index maps to the evt.which value 索引映射到evt。哪个值的图像参考数组怎么样

var images=[];
images[64]='a.jpg';
images[65]='b.jpg';
images[66]='c.jpg';
//...etc...

$(window).keydown(function(evt) {
    var image=images[evt.which]'
    if(image){
        alert(image);
    }
})

A bit ugly, probably not the most efficient, but easy to follow :) 有点丑陋,可能不是最有效的,但易于遵循:)

I would get the key value and then just match it again az. 我将获取键值,然后再次将其匹配az。 Try something like: 尝试类似:

$(window).keydown(function(e) {
    var key = String.fromCharCode(e.which).toLowerCase();
    if(/[a-z]/i.test(key)) {
        alert(key+'.jpg');
    }
});

Demo: http://jsfiddle.net/BMZaF/ 演示: http//jsfiddle.net/BMZaF/

Seems that event.which for letters corresponds to the ASCII value. 似乎该事件。字母对应于ASCII值。 So, you could do something like the following: 因此,您可以执行以下操作:

$(window).keydown(function(evt) {
  if (evt.which >= 65 && evt.which <= 90){
    $('img[src="' + String.fromCharCode(evt.which).toLowerCase() + '.jpg"]').show();        
  }
});

You should named your image files with the alphabet KeyCodes. 您应该使用字母KeyCodes命名图像文件。

For instance the entered letter "a" must be named "97.jpg". 例如,输入的字母“ a”必须命名为“ 97.jpg”。

So you can call it from your jquery like this: 因此,您可以像这样从您的jquery调用它:

$(document).ready(function(){
    $("#input").bind('keypress', function (e) {
        console.log(e.which);  //or alert(e.which);  
        $("#Image").attr("src", e.which + ".jpg");
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM