老师,我这段代码没看懂
来源:5-1 事件参数
qq_慕粉6009927
2020-10-13 20:53:54
$(document).keydown(function(event){
if (event.keyCode == 37) {
if (index == 0) {
index = $('a').length-1;
}else{
index--;
}
swiper();
}
else if (event.keyCode ==39) {
if (index == $('a').length-1) {
index = 0;
}
else{
index++;
}
swiper();
}
});
1回答
好帮手慕星星
2020-10-14
同学你好,问题解答如下:
1、代码中给document文档绑定了键盘事件keydown,按下键盘的时候就会执行
2、每个键对应着自己的keyCode码,上下左右键中的左键keyCode码为37,右键的keyCode码为39 ,所以代码中进行了判断
3、当按左键的时候,index索引减1,执行swiper方法切换图片,但是还需要添加临界判断,当是第一张图片的时候,index索引变为最后一张,保证切换正常。右键也是一样的,按下右键,index索引加1,执行swiper方法切换图片,添加临界判断,当是最后一张的时候,index索引变为第一张。
也可以参考下面代码中的注释:
<script>
// document文档绑定了键盘事件keydown,按下键盘的时候就会执行
// 每个键对应着自己的keyCode码,上下左右键中的左键keyCode码为37,右键的keyCode码为39 ,所以代码中进行了判断
$(document).keydown(function(event) {
// 当按左键的时候,
if (event.keyCode == 37) {
// 还需要添加临界判断, 当是第一张图片的时候,
if (index == 0) {
// index索引变为最后一张, 保证切换正常
index = $('a').length - 1;
} else {
// index索引减1
index--;
}
// 执行swiper方法切换图片
swiper();
// 右键也是一样的,按下右键,
} else if (event.keyCode == 39) {
// 添加临界判断,当是最后一张的时候
if (index == $('a').length - 1) {
// index索引变为第一张
index = 0;
} else {
// index索引加1
index++;
}
// 执行swiper方法切换图片
swiper();
}
});
</script>祝学习愉快!
相似问题