简体   繁体   English

通过按键箭头更改图像不起作用。

[英]Change image by key arrows is not working.

I created function to change images by clickiking arrows. 我创建了通过单击箭头来更改图像的功能。 My functions is not working. 我的功能不起作用。 Can you give me some hints? 你能给我一些提示吗?

You can find my code below: 您可以在下面找到我的代码:

 var imgs = [ "assets/1.jpg", "assets/2.jpg", "assets/3.jpg", "assets/4.jpg", "assets/5.jpg", "assets/6.jpg", "assets/7.jpg" ]; function changeImage() { var img = document.getElementById("images"); img_index = ++img_index % 7; img.src = imgs[img_index]; } function checkKey(e) { e = e || window.event; if (e.keyCode == '37') { // left arrow changeImage(); } else if (e.keyCode == '39') { // right arrow changeImage(); } } // document.onkeydown = checkKey(); 
 <img id="images" src="assets/1.jpg" /> 

Thank you, Megi 谢谢Megi

You have multiple problems with your script. 您的脚本有多个问题。

  • Remove the () on the end of this line document.onkeydown = checkKey(); 卸下()在该行的末尾document.onkeydown = checkKey(); . Like you did it you will directly call the function instead of assignin it to the event. 就像您所做的一样,您将直接调用该函数,而不是将其分配给事件。

  • The img_index value is not defined in your example and therefore it fails. 在您的示例中未定义img_index值,因此它失败。 You could just set it to 0 at the start. 您可以在开始时将其设置为0

 var img_index = 0; var imgs = [ "assets/1.jpg", "assets/2.jpg", "assets/3.jpg", "assets/4.jpg", "assets/5.jpg", "assets/6.jpg", "assets/7.jpg" ]; function changeImage() { var img = document.getElementById("images"); img_index = ++img_index % 7; img.src = imgs[img_index]; } function checkKey(e) { e = e || window.event; if (e.keyCode == '37') { // left arrow changeImage(); } else if (e.keyCode == '39') { // right arrow changeImage(); } } document.onkeydown = checkKey; 
 <img id="images" src="assets/1.jpg" /> 

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

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