문제

Why this code don't work properly?

<img src="picture.jpg" id="picture"/>

<script>
document.getElementById('picture').onkeydown = function() {alert('tekst');}
</script>
도움이 되었습니까?

해결책

Your image doesn't have focus so it won't listen to the 'onkeydown' event. I'm not sure if it is possible to give an image focus in order for your onkeydown event to work.

Instead you could place your image within an a-tag which can have focus and therefore can listen to the onkeydown event.

Something like this:

<a id="picture" href="#">
    <img src="picture.jpg" />
</a>

<script>
   // The a tag
   var picture = document.getElementById('picture');
   // You have to put focus on the atag (or any element that you want to have for you onkeydown event.
   picture.focus();
   // Now your event will work
   picture.onkeydown = function() {
       alert('tekst');
   }
</script>
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top