键盘箭头在 4 个方向上浏览图像

Keyboard arrow navigation through images in the 4 directions

我一直在为 uni 做一个项目,虽然我熟悉 HTML 和 CSS,但我对 js 的了解非常模糊。

我现在正在尝试制作某种画廊,您可以在其中使用键盘箭头浏览图像,这些图像有时会在 4 个方向中的任何一个方向上分支,将其视为 'Choose Your Own Adventure' 书,但我我有点卡住了。

喜欢this, where every frame covers the whole screen and you navigate through it like the first answer here:但在任何方向只要那里有另一个框架。

See comments and links below!

这是一个丑陋但有效的解决方案,如果您是新手,它可能会对您的学习有所帮助:

var coord = function (name, isPass,x,y) {
    return {
        name: name,
        pass: isPass | false,
        x:x,
        y:y
    }
}
var map = [
    [
        new coord("x:0,y:0", true,0,0),
        new coord("x:1,y:0", true,1,0)
    ],
    [
        new coord("x:0,y:1", false,0,1),
        new coord("x:1,y:1", true,1,1)
    ],
]
const notPossibleCoord = new coord("", false, -1, -1);
var currentPosition = new coord("", false, -1, -1);
function tryMove(direction) {    
    var nextDirection;
    try {
        switch (direction) {
            case "top": nextDirection = map[currentPosition.x][currentPosition.y + 1]; break;
            case "bottom": nextDirection = map[currentPosition.x][currentPosition.y - 1]; break;
            case "left": nextDirection = map[currentPosition.x - 1][currentPosition.y]; break;
            case "right": nextDirection = map[currentPosition.x + 1][currentPosition.y + 1]; break;
            default:
                return notPossibleCoord
        }
        if (nextDirection.pass)
            return nextDirection;
        else
            return notPossibleCoord;
    } catch (e) {
        //index out of range, it's your edge
        return notPossibleCoord;
    }
}

function onArrowPress() {
    var prevPosition = currentPosition;
    currentPosition = tryMove("top");
    if (currentPosition == notPossibleCoord)
        return; //do nothing if movement not possible

    //do what you need to do
}

一些评论:

  1. 我们声明订阅坐标项的函数对象
  2. 创建您的地图(在您的案例中,地图将由 'images-nodes' 创建)
  3. create const not possible (注意!它需要 ES6(可能是 ES2015),因此,您可以只使用 [= 而不是 const 13=];
  4. 声明函数tryMove - 这是你移动的主要函数
  5. 设置 document.keyPress 或某些事件我们的函数 onArrowPress,检查是否 'arrow',然后执行您的逻辑

您需要了解的内容仅此而已:

  1. Using an Object Constructor
  2. JavaScript Arrays
  3. JavaScript Switch Statement
  4. JavaScript Errors
  5. onkeypress Event
  6. JavaScript HTML DOM