3

我想制作一个表单,在发送之前使用 JavaScript 验证数据。当一个字段为空时,我想将其边框设置为红色。

HTML 代码:

<label>Question: </label><input type = "text" maxlength = "100" name = "question"> <br />

JavaScript 代码 1:

fields[i].style.borderColor = "red";

JavaScript 代码 2:

fields[i].style.border = "1px solid red";

如果我使用 JS 代码 1,边框会改变它的颜色,但它的宽度比以前大(尽管我没有说任何关于边框宽度的内容)。如果我使用 JS 代码 2,文本输入会缩小 2px,并且变化很明显。

我应该怎么做才能只更改边框颜色?

4

5 回答 5

4

实际上,这是通过添加和删除类的首选:

$("input").change(function()
  {
     var value = $(this).val();
     if(value=="")
     {
          $(this).addClass("red-border");
          $(this).focus();
     }else
     {
          $(this).removeClass("red-border");
     }
  });

还有你的 CSS:

.red-border{
    border: 1px solid red;
}
于 2013-11-08T20:16:21.383 回答
4

The default user agent stylesheet uses this for the input field:

border: 2px inset;

Now you may ask why is this not defined by default?

by default(In IE the appreance is hard-coded):

appearance: textfield;

But whenever you change something:

appearance: none;

And when the appearance is none, you will see the 2px inset border.

So actually the width is the problem here:

So you want to change 2 propeties: Border-width and border-color
You would need 2 lines now:

document.getElementsByTagName('input')[0].style.border = "red";
document.getElementsByTagName('input')[0].style.borderWidth = "1px";

jsFiddle

However your own solution might be elegant, as it is defined with one line of code:

fields[i].style.border = "1px solid red";


Note that the inset style sets the top and right border lighter where the bottom and left border is the given color. Setting the style to solid will solve this.

It won't harm your code to use the whole shorthand property of border. You always have to be very specific when you want to win the battle with the user agent stylesheet.

于 2013-11-08T20:50:16.717 回答
1

使用轮廓而不是边框​​。

fields[i].style.outline = "1px solid red";

于 2013-11-08T21:02:13.103 回答
1

我在生产中有这样的东西,只是它使用警报而不是颜色变化。使用 CSS 样式和类:

CSS

.error {
    border:2px solid red;
}

JavaScript

<script>
function checkField(){
    var f = document.getElementById('<name of field>').value;
    if (f === "") {
       document.getElementById('<name of field>').className = document.getElementById('<name of field>').className + " error";
       return false;
    }
}
</script>

然后将此添加到您的按钮/控件的单击事件中:

return checkField()

这个 SO 帖子似乎很相似:使用 javascript 更改文本框边框颜色

于 2013-11-08T20:25:19.807 回答
0

试试这个。jQuery

 $("input").change(function ()
  {
     var value = this.value;
     if(value=="")
     {
          $(this).css("border", "1px solid red");
     }else
     {
        $(this).css("border",'');
     }
  }).trigger("change");

html

  <input type="text" class="col"> 
于 2013-11-08T20:08:52.370 回答