首页 > 解决方案 > 填字游戏焦点不会在带有数字的输入中移动,尝试将包装器和数字放在 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

此外,如果您对如何上下移动箭头有任何想法,那就太好了。

谢谢!

标签: jqueryinputfocuscrossword

解决方案


当输入元素具有父 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();
}

您可以将相同的逻辑应用于您需要的其余击键


推荐阅读