javascript - 通过键盘箭头在 4 个方向上浏览图像

标签 javascript html navigation arrows

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

我现在正在尝试制作某种画廊,您可以使用键盘箭头浏览有时在 4 个方向中的任何一个分支的图像,将其视为一本“选择您自己的冒险”书,但我'我有点卡住了。

喜欢this ,其中每一帧都覆盖整个屏幕,您可以像第一个答案 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. 创建您的 map (在您的情况下, map 将由“images-nodes”创建)
  3. create const 不可能 (小心!它需要 ES6(可能是 ES2015),因此,您可以使用而不是 const var;
  4. 声明函数 tryMove - 这是移动的主要函数
  5. 设置 document.keyPress 或某个事件我们的函数 onArrowPress,检查它是否为“箭头”,然后执行您的逻辑
<小时/>

您需要了解的内容就是:

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

关于javascript - 通过键盘箭头在 4 个方向上浏览图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43731040/

相关文章:

javascript - iframe点击后才显示?

javascript - AngularJS:导航栏

css - 如何在调整寡妇大小时锁定导航位置?

javascript - 无法将 Solidity 合约部署到 Rinkeby 网络(无效的 asm.js : Invalid member of stdlib)

javascript - 为什么只能调整我最近添加的页面元素的大小?

html - 如何才能将左边的文字正确对齐到一行的列中?

Android:以步行模式开始导航

javascript - 胜利图: dynamic width dependent on axis label width

javascript - 我有一个 Uncaught Reference Error 说一个函数没有定义,尽管它似乎被定义了

javascript - IT Hit cookies 通行证问题