为了账号安全,请及时绑定邮箱和手机立即绑定

js中键盘事件

 document.onkeydown = function (event) {

       

        event = event || window.event;

        p = as.length;//p=5

        if (event.keyCode == 40) {//向下键

            event.preventDefault ? event.preventDefault() : event.returnValue = false;

            index++;

            as[index].style.background = 'gray';

            as[index - 1].style.background = 'white';

            if (index > as.length - 1) {

                index = 0;

                 as[index].style.backgroundColor = "gray";

            }

           

        }

    http://img1.sycdn.imooc.com//57a087490001481502440184.jpg为什么用向下键到最后一行的时候回不到一个行了?我明明设置好了 index到as.length的时候就令inde=0;为什么执行的时候不可以?

正在回答

2 回答

我在你的代码中添加了console.log(index);

http://img1.sycdn.imooc.com//57a1bfa70001380805120322.jpg

http://img1.sycdn.imooc.com//57a1bfe7000190aa06010199.jpg

控制台爆出错误(后面部分没有截取)。我不清楚你的index的初始值是为0还是-1,根据你的代码来看,应该是从-1开始,那么第一个TypeError错误是因为——即使最开始index++(index = 0),但是as[index - 1]也就是as[-1]不存在。第二个TypeError同样如此,根据你所写的代码,as.length = 5,换言之 if(index > 4)才会执行if内部的代码。假设此刻index为4,if判断为false,按下down键,

index++  ——>index = 5

as[index].style.background = "gray" ——>相当于as[5].style.background = "gray"

然而问题就在于这,数组的下标越界,因此一直卡在这里,无法执行下面的代码,因此if条件内部的代码无法生效,所以向下键到最后一行的时候回不到第一行。

稍微修改了下你的代码,在我的浏览器上测试成功了。

document.onkeydown = function (event) {
   event = event || window.event;
   p = as.length;
   if (event.keyCode == 40) {
       event.preventDefault ? event.preventDefault() : event.returnValue = false;
       if(index == -1)
       {
           as[p - 1].style.backgroundColor = "white";
       }
       index++;
       as[index].style.background = 'gray';
       as[index - 1].style.background = 'white';
       if (index == as.length - 1) {
           as[index - 1].style.backgroundColor = "white";
           as[index].style.backgroundColor = "gray";
           index = -1;
       }
       console.log(index)
   }
};

不过这样写总觉得逻辑上有些混乱,但是改动不大,楼主理解应该也比较容易。

2 回复 有任何疑惑可以回复我~

if (index > as.length - 1) 提前到as[index].style.background = 'gray'前面试试,会不会是as[index]中的index大于了as.length导致的?比如6的时候

0 回复 有任何疑惑可以回复我~

举报

0/150
提交
取消
DOM事件探秘
  • 参与学习       99547    人
  • 解答问题       1197    个

DOM事件?本课程会通过实例来给小伙伴们讲解如何使用这些事件

进入课程

js中键盘事件

我要回答 关注问题
意见反馈 帮助中心 APP下载
官方微信