【问题标题】:Jquery return new focus when switching with the tab button使用选项卡按钮切换时 Jquery 返回新焦点
【发布时间】:2016-06-08 14:28:12
【问题描述】:

我有一个函数可以在页面上的元素之间更改焦点时添加/删除一个类。

当用鼠标点击切换焦点时,会产生想要的效果,但是当用标签按钮切换时,它似乎在切换到新元素之前读取焦点?

HTML:

 <div class="text-input">
    <label>First Name</label>
    <input placeholder="">
</div>

<div class="text-input">
     <label>First Name</label>
    <input placeholder="">
</div>

JS:

$(document).ready(function () {
    $("body").click(function () {activateInput($(this))});
    $('body').keydown(function(e) {
         var code = e.keyCode || e.which;
        if (code == '9') {activateInput($(this))}
    });
});


function activateInput(passThis) {
    $(".text-input input, .text-input label").removeClass("active");
    if ($(".text-input input").is(":focus")) {
    $(":focus").parent().children("label, input").addClass("active");
    }
}

小提琴: https://jsfiddle.net/4kdj7Luc/

【问题讨论】:

    标签: javascript jquery input focus


    【解决方案1】:

    使用keyup

    $(document).ready(function () {
    
        $("body").click(function () {activateInput()});
        $('body').keyup(function(e) {
            var code = e.keyCode || e.which;
            if (code == 9) {activateInput();}
        });
    });
    
    
    function activateInput() {
        $(".text-input input, .text-input label").removeClass("active");
        $(':focus').parent().children("label, input").addClass("active");
    }

    【讨论】:

    • 呃。我怎么没想到呢?谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 2014-08-07
    • 2011-02-22
    • 1970-01-01
    相关资源
    最近更新 更多