繁体   English   中英

使用Jquery关注输入并移除焦点

[英]Focus on input and remove focus using Jquery

我想要检查输入是否有焦点为背景添加颜色然而当我移除鼠标并专注于另一个输入时它不再移除焦点它实际上保持焦点! 如何从第一个中移除背景!

Fullname: <input type="text" name="name"><br>
Email: <input type="text" name="email">

如何检查类测试是否存在

由于某些原因我没有工作,我正在追随以下if声明。 我的代码可能有问题,我出于某种原因无法发现!

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
});

如果你可以为我测试一下,或者让我知道上面的代码出了什么问题,我会尽快给它!

你可以使用.blur

$(document).ready(function(){
    $("input").focus(function(){
        $(this).css("background-color", "#f4fcef");
    });
    $("input").blur(function(){
        $(this).css("background-color", "#ffffff");
    });
});

或者您可以在html代码的每个部分添加类:

Name: <input class="name" type="text" name="fullname"><br>
Email: <input class="email" type="text" name="email">

并使用以下JQuery代码来运行它。

$(document).ready(function(){
    $(".name").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".email").css("background-color", "#ffffff");        
    });
    $(".email").focus(function(){
        $(this).css("background-color", "#f4fcef");
        $(".name").css("background-color", "#ffffff");        
    });
});

为了更好的方式,您可以使用CSS:

input:focus {
    background-color: yellow;
}

但使用jquery:

$('input[type="text"]').focus(function() {
    $(this).css("background-color", "#cccccc");
});

$('input[type="text"]').blur(function() {
    $(this).css("background-color", "#fff");
});

您可以检查焦点是否存在于焦点上,然后在焦点上执行相同的操作。

 $(document).ready(function(){
$("input").focus(function(){
    if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");
    }

}).focusout(function(){
   if($(this).hasClass("yourclassName")){
     $(this).css("background-color", "#f4fcef");//some other color.
    }
});

});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM