我一直在为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
}
一些评论:
- 我们声明订阅坐标项的函数对象
- 创建您的 map (在您的情况下, map 将由“images-nodes”创建)
- create const
不可能
(小心!它需要 ES6(可能是 ES2015),因此,您可以使用而不是const
var
; - 声明函数
tryMove
- 这是移动的主要函数 - 设置
document.keyPress
或某个事件我们的函数onArrowPress
,检查它是否为“箭头”,然后执行您的逻辑
您需要了解的内容就是:
关于javascript - 通过键盘箭头在 4 个方向上浏览图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43731040/