【问题标题】:Set a class for a textbox on focus using Javascript使用 Javascript 为焦点上的文本框设置一个类
【发布时间】:2015-01-11 22:09:09
【问题描述】:

我有以下 HTML 引导代码

 <div class="form-group">
            <label class="col-sm-2 control-label labelfont">FIRST NAME:</label>
            <div class="col-sm-6">
               <input type="text" class="form-control" placeholder="Enter the First Name" id="FirstName" onkeypress="return onlyAlphabets(event);">
            </div>
            <label class="col-sm-4 labelfont errorMsg" id="Err_FirstName">Enter the first name</label>
        </div>

我在Tabout上的JS代码如下

$("#FirstName").blur(function () {
    if ($(this).val().trim().length == 0)
    {
        $(this).addClass('borderclass');
        $("#Err_FirstName").show();   
    }
    else {
        $("#Err_FirstName").hide();
        $(this).removeClass('borderclass');
    }
});

'borderclass'如图所示

.borderclass
{ 
     border:1px solid red;
}

上面的代码在 Tab out 上运行良好。

但是在将焦点移回控件以输入值时,我再也看不到红色边框了。

我认为 bootstrap 对每个控件都有自己的 css,当焦点回到控件时会设置它。为了解决这个问题,我尝试了以下方法,但没有成功

  $("#FirstName").focusin(function () {
    if($("#Err_FirstName").visible)
        $(this).addClass('borderclass');
});

任何正确方向的帮助将不胜感激。非常感谢。

【问题讨论】:

    标签: javascript jquery html css twitter-bootstrap


    【解决方案1】:

    样式被引导程序覆盖,你可以添加这个

    .borderclass:focus {
        border: 1px solid red;
        box-shadow: 0px 0px 2px 0px red;
        outline: 0;
    }
    

    演示 - http://www.bootply.com/XpOUxMMhdT

    【讨论】:

    • 非常感谢维托里诺
    • 关于另一个话题,你能告诉我如何对齐错误消息标签上的文本,使其居中
    • 您可以使用.form-horizontal 类而不是.form-group 它将对齐label vertically 但您需要align text-left bootply.com/XpOUxMMhdT @AbhishekKS
    【解决方案2】:

    jQuery 对象中没有 visible 属性。但是有 $.fn.is 可以满足您的需求。也就是说,您可以使用伪选择器 :visible 作为返回布尔值的 is 方法中的参数。

    $("#FirstName").focusin(function () {
       if($("#Err_FirstName").is(":visible"))
          $(this).addClass('borderclass');
    }
    

    【讨论】:

    • 我刚试过。不幸的是它没有用。请看我的编辑。我已经添加了相同的图片。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-23
    • 1970-01-01
    • 1970-01-01
    • 2010-11-23
    • 1970-01-01
    相关资源
    最近更新 更多