题解 | #移动控制#
移动控制
http://www.nowcoder.com/practice/84af7932f53f4bbeaa1fa079a138bb35
function bind(){
document.onkeydown = function(event){
if (!event) return;
var code = event.keyCode || '';
if (!{'37': 1, '38': 1, '39': 1, '40': 1}[code]) return;
event.preventDefault && event.preventDefault();
var c = document.querySelector('.current');
var index = '';
Array.prototype.forEach.call(c.parentElement.children,function(item,i){
if(item.className == 'current'){
index = i;
}
});
c.className = '';
switch(code){
case 37:
if(c.previousElementSibling){
c.previousElementSibling.className = 'current';
break;
}
else{
c.parentElement.children[c.parentElement.children.length - 1].className = 'current';
break;
}
case 39:
if(c.nextElementSibling){
c.nextElementSibling.className = 'current';
break;
}
else{
c.parentElement.children[0].className = 'current';
break;
}
case 38:
if(c.parentElement.previousElementSibling){
c.parentElement.previousElementSibling.children[index].className = 'current';
break;
}
else{
c.parentElement.parentElement.children[c.parentElement.parentElement.children.length - 1].children[index].className = 'current';
break;
}
case 40:{
if(c.parentElement.nextElementSibling){
c.parentElement.nextElementSibling.children[index].className = 'current';
break;
}
else{
c.parentElement.parentElement.children[0].children[index].className = 'current';
break;
}
}
}
}
}
主考节点应用。