繁体   English   中英

使用 jQuery 使用右/左箭头键导航幻灯片

[英]Navigate slideshow with right/left arrow keys using jQuery

这是我用 jQuery 制作的幻灯片。 如何使用键盘上的左右键执行与单击事件相同的操作?

var x = 0;
$("#right-arrow").click(function(){
  if (x<3){
    x = x + 1;
    $("#wrapper").animate({ top: '-=400px' }, 1000);
  };
});
$("#left-arrow").click(function(){
  if (x>0){
    x = x - 1;
    $("#wrapper").animate({ top: '+=400px' }, 1000);
  };
});

应该有效:

var x = 0;
document.addEventListener("keydown", event => {
  //every time a key is pushed, this function will fire
  event.code === "ArrowLeft" && moveLeft();
  event.code === "ArrowRight" && moveRight();
});

$("#right-arrow").click(function() {
  moveRight();
});
$("#left-arrow").click(function() {
  moveLeft();
});

function moveLeft() {
  if (x > 0){
    x = x - 1;
    $("#wrapper").animate({ top: '+=400px' }, 1000);
  }
}
function moveRight() {
  if (x < 3){
    x = x + 1;
    $("#wrapper").animate({ top: '-=400px' }, 1000);
  }
}

键盘输入通常与以下事件绑定: keydownkeyupkeypress 您可以使用它们中的任何一个,并通过检查其code属性来检查按下了哪个键。 您不应使用keyCode属性,因为它已被弃用。

编辑:从评论中了解到, keypress事件已被弃用。 所以避免再使用它。

JavaScript 关键代码在这里

$(document).keydown(function(e) {
  if (e.code == 37)//left arrow
  {
   //your logic for left arrow press
  }
  if (e.code == 39)//rightarrow
  {
   //your logic for right arrow press
  }
});

暂无
暂无

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

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