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";
? ? ? ? ? ? }
? ? ? ? ? ?
? ? ? ? }
????為什么用向下鍵到最后一行的時(shí)候回不到一個(gè)行了?我明明設(shè)置好了 index到as.length的時(shí)候就令inde=0;為什么執(zhí)行的時(shí)候不可以?
2016-08-03
我在你的代碼中添加了console.log(index);
控制臺(tái)爆出錯(cuò)誤(后面部分沒(méi)有截?。?。我不清楚你的index的初始值是為0還是-1,根據(jù)你的代碼來(lái)看,應(yīng)該是從-1開(kāi)始,那么第一個(gè)TypeError錯(cuò)誤是因?yàn)椤词棺铋_(kāi)始index++(index = 0),但是as[index - 1]也就是as[-1]不存在。第二個(gè)TypeError同樣如此,根據(jù)你所寫的代碼,as.length = 5,換言之 if(index > 4)才會(huì)執(zhí)行if內(nèi)部的代碼。假設(shè)此刻index為4,if判斷為false,按下down鍵,
index++ ?——>index = 5
as[index].style.background = "gray" ——>相當(dāng)于as[5].style.background = "gray"
然而問(wèn)題就在于這,數(shù)組的下標(biāo)越界,因此一直卡在這里,無(wú)法執(zhí)行下面的代碼,因此if條件內(nèi)部的代碼無(wú)法生效,所以向下鍵到最后一行的時(shí)候回不到第一行。
稍微修改了下你的代碼,在我的瀏覽器上測(cè)試成功了。
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)
? ?}
};
不過(guò)這樣寫總覺(jué)得邏輯上有些混亂,但是改動(dòng)不大,樓主理解應(yīng)該也比較容易。
2016-08-03
if (index > as.length - 1) 提前到as[index].style.background = 'gray'前面試試,會(huì)不會(huì)是as[index]中的index大于了as.length導(dǎo)致的?比如6的時(shí)候