简体   繁体   中英

Adding an event listener to an image

I have been working on a small project where I have to resize a car. However, whenever I press the left arrow, the car is supposed to resize, but nothing happens. This is my Javascript code:

var car = document.getElementById('cr');

 car.addEventListener("keydown",function(event){

  if(event.which == 37){
 //left
console.log('left');
car.style.width = 10 + "px";

 }

if(event.which == 39){
//right
}
})

The event listener is on the image so it will only fire if the image has the focus when a key is pressed down. (That or a descendant element, but images can't have descendants).

Images can't, by default, have the focus anyway.

Attach the event listener to the window object instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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