问题
I've only been working with JavaScript, and programming in general, for about a month now and came across a problem which I just can't find a solution to. So here I am. I've created a gallery where you can click small images to zoom them up in a new "window" (it's just a div placed ontop of the rest of the page) for a better view of the picture.
And here's the tricky part. I want to be able to change image when I press the arrow keys. For example, if I press the right arrow key on my keyboard I want the old picture to turn hidden and the second image in line to fade in.
Here's the code for when you press the arrow keys:
function onKeyPress(e)
{
if (e.keyCode == 37) {
lastImage.hide();
indexNum--;
$("#zoomImage img").attr('src', picSrc[indexNum]).fadeIn();
}
if (e.keyCode == 39) {
lastImage.hide();
indexNum++;
$("#zoomImage img").attr('src', picSrc[indexNum]).fadeIn();
}
}
And here's the code for the variables:
lastImage = $(#zoomImage img"); //The last picture shown)
var picSrc = ["img1.png", "img2.png", "img3.png"];
回答1:
the code seems to be correct to me, please cross check weather the function is called on key press and the variable are accessible inside by using alert method for debugging.
来源:https://stackoverflow.com/questions/12656645/change-image-when-pressing-arrow-keys