jquery - 填字游戏焦点不会在带有数字的输入中移动,尝试将包装器和数字放在 jQuery 函数中
问题描述
我正在做一个填字游戏,并试图让焦点用箭头键左右移动,在输入一个字母后,但它卡在了里面有数字的方块上。
这就是我的 html 中带有数字的 div 的样子。
enter co<div><input class="letter" type="text" disabled /> </div>
<div><input class="letter" type="text" disabled /> </div>
<div class="wrapper">
<input class="letter hideletter" type="text" maxlength="1" value="" placeholder="D" />
<span class="num">1</span>
</div>
<div><input class="letter" type="text" disabled /> </div>
<div><input class="letter" type="text" disabled /> </div>
查询:
//makes arrow keys work, but only works right to left and left to right at this point
$(document).keydown(
function (e) {
//makes focus jump to next input when a letter is typed
$(".hideletter:focus").on('input', function() {
$(".hideletter:focus").next().focus();
});
switch (e.which) {
case 39: //right
$(".hideletter:focus").next().focus();
$(".num:focus").next().focus();
break;
case 40: //down doesn't work
$(".hideletter:focus").next().focus();
$(".num:focus").next().focus();
break;
case 37: //left
$(".hideletter:focus").prev().focus();
$(".num:focus").prev().focus();
break;
case 38: //up doesn't work
$(".hideletter:focus").next().focus();
$(".num:focus").next().focus();
break;
default: return; // exit this handler for other keys
}
e.preventDefault(); // prevent the default action (scroll / move caret)
});
这是填字游戏的链接。 https://jenniferlang1921.github.io/Crossword2/
这是我的代码的链接: https ://github.com/JenniferLang1921/Crossword2
此外,如果您对如何上下移动箭头有任何想法,那就太好了。
谢谢!
解决方案
当输入元素具有父 div 时,您的代码将中断,因为焦点将始终转到下一个元素,这意味着下一个元素将始终<span class="num">4</span>
为了修复它,您必须检查当前元素是否有任何父元素,如果有父元素,则更改父元素旁边的焦点。
switch (e.which) {
case 39:
var focusedElement= $(document.activeElement);
if(focusedElement.parent().hasClass('wrapper')){
focusedElement.parent().next().focus();
}
else{
$(".hideletter:focus").next().focus();
$(".num:focus").next().focus();
}
您可以将相同的逻辑应用于您需要的其余击键
推荐阅读
- selenium - Xpath 不工作,我正在使用 appium 来定位 xpath
- php - 如何解决:已经定义的“路由名称未定义”
- javascript - 如何将单个 [x, y] 坐标转换为 [xstart, xend,ystart,yend] 的范围?
- c - 如何使用 prolog 调用酷图库函数?
- mysql - 当所有表都没有主键时使用“SET”更新多列
- reactjs - 为什么我需要将 React/Enzyme 状态更改包装在 act 中?
- php - PHP 7.3.8。MacOS Catalina 10.15 上的 ZIP 扩展
- java - 为什么这一行给我关于 getDownloadUrl() 方法的错误我该如何解决
- javascript - 通过导航时无法获取参数
- c - 该代码应该将每个单词的每个字母都转换为大写。但是运行代码会导致总线错误。是什么导致总线错误?