使用箭头键浏览4x4网格?

时间:2013-03-27 23:08:02

标签: javascript navigation

我在这里阅读了这个答案Guide for writing arrowkey navigation on focusable elements?,但它不够详细,不适合像我这样的新手理解。

我需要像这样的东西,我的DOM中有一个带有div的4x4网格。我希望能够在选择器中移动,然后能够使用enter选择聚焦div。

编辑:粘贴了一些代码,

当我意识到自己处于完全错误的轨道时,这就是我的尝试:

function arrowKeys(input){
    var keyCode = input.keyCode;
    var border = document.getElementById(keyid);
    var removeBorder = border.removeAttribute("style");

    if(keyCode == 38 || keyCode == 39 || keyCode == 40 || keyCode == 37){
        var addborder = border.setAttribute("style", "border:2px solid red");
        border.addborder;
        if(keyCode == 38){
            removeBorder;
            keyid = keyid - 4;
            border.addborder;
            console.log(keyid + " upp");
        }
        if (keyCode == 39){
            removeBorder;
            keyid++;
            border.addborder;
            console.log(keyid + " right");
        }
        if(keyCode == 40){      // right arrowkey
            removeBorder;   
            keyid = keyid + 4;
            border.addborder;
            console.log(keyid + " down");
        }
        if (keyCode == 37){     // left arrowkey
            removeBorder;
            keyid--;
            border.addborder;
            console.log(keyid + " left");
        }
    }
}

我认为你需要在这样的行上使用数组,

var navigationMap = [[1,2,3,4][5,6,7,8][9,10,11,12][13,14,15,16]];

但是我坚持这样的事情......

2 个答案:

答案 0 :(得分:0)

我用jQuery完成了这个。您可以使用以下内容连接到事件:

  $(".some-css-class-on-your-divs").keydown(function (e)
  {
    HandleKeyDown(e, $(this));
  })

然后用另一个javascript方法处理事件

function HandleKeyDown(event, jqNode)
{
  event = event || window.event;
  var charCode = event.charCode || event.keyCode;


  if (charCode == 40)
  { // down arrow key
      ///  do your thing here
  }
   // charcode 38 is up, and so on
}

答案 1 :(得分:0)

这是使用普通javascript执行此操作的方法。代码的第一部分是一些跨浏​​览器函数,用于添加事件处理程序和添加/删除类。你会注意到我添加/删除一个类来显示活动项而不是直接添加/删除一个样式。这将样式放在CSS而不是javascript中,这通常是一个好主意。

工作演示: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;
        }
    });
})();