更新时间:2023-11-26 10:31:46
这是使用普通javascript做到这一点的一种方法.代码的第一部分是一些跨浏览器功能,用于添加事件处理程序和添加/删除类.您会注意到,我添加/删除了一个类以显示活动项目,而不是直接添加/删除样式.这会将样式放在CSS中,而不是在javascript中,这通常是个好主意.
Here's a way to do this using plain javascript. The first part of the code is some cross browser functions to add event handlers and add/remove classes. You'll notice that I add/remove a class to show the active item rather than directly adding/removing a style. This puts the style in the CSS rather than in the javascript which is generally a good idea.
正在运行的演示: http://jsfiddle.net/jfriend00/yMMxX/
(function() {
// refined add event cross browser
function addEvent(elem, event, fn) {
if (typeof elem === "string") {
elem = document.getElementById(elem);
}
// avoid memory overhead of new anonymous functions for every event handler that's installed
// by using local functions
function listenHandler(e) {
var ret = fn.apply(this, arguments);
if (ret === false) {
e.stopPropagation();
e.preventDefault();
}
return(ret);
}
function attachHandler() {
// set the this pointer same as addEventListener when fn is called
// and make sure the event is passed to the fn also so that works the same too
var ret = fn.call(elem, window.event);
if (ret === false) {
window.event.returnValue = false;
window.event.cancelBubble = true;
}
return(ret);
}
if (elem.addEventListener) {
elem.addEventListener(event, listenHandler, false);
} else {
elem.attachEvent("on" + event, attachHandler);
}
}
function addClass(elem, cls) {
var oldCls = elem.className;
if (oldCls) {
oldCls += " ";
}
elem.className = oldCls + cls;
}
function removeClass(elem, cls) {
var str = " " + elem.className + " ";
elem.className = str.replace(" " + cls + " ", " ").replace(/^\s+|\s+$/g, "");
}
function findItem(items, target) {
for (var i = 0; i < items.length; i++) {
if (items[i] === target) {
return(i);
}
}
return(-1);
}
var keys = {up: 38, down: 40, left: 37, right: 39};
var cards = document.getElementById("game-board").getElementsByClassName("card");
addEvent(document, "keydown", function(e) {
// get key press in cross browser way
var code = e.which || e.keyCode;
// number of items across
var width = 4;
var increment, index, newIndex, active;
switch(code) {
case keys.up:
increment = -width;
break;
case keys.down:
increment = width;
break;
case keys.left:
increment = -1;
break;
case keys.right:
increment = 1;
break;
default:
increment = 0;
break;
}
if (increment !== 0) {
active = document.getElementById("game-board").getElementsByClassName("active")[0];
index = findItem(cards, active);
newIndex = index + increment;
if (newIndex >= 0 && newIndex < cards.length) {
removeClass(active, "active");
addClass(cards[newIndex], "active");
}
// prevent default handling of up, down, left, right keys
return false;
}
});
})();