使用 jquery 更改占位符文本字体和颜色

Ahm*_*med 4 html forms jquery input

我有以下形式的输入标签

<input type="text" name="firstname" id="firstname" placeholder="First name">
Run Code Online (Sandbox Code Playgroud)

首先,我使用 jquery 检查该字段是否为空

 $("#submitreg").click(function(e){
     if ($.trim($("#firstname").val())=='')
         {
             $("#firstname").attr('placeholder',"first name can't be empty");
             e.preventDefault();
         }
 });
Run Code Online (Sandbox Code Playgroud)

现在,如果输入字段为空,我将占位符更改为“名字不能为空”。是否也可以将占位符颜色更改为红色并使用 jquery 将字体设为 85%。

谢谢

Edd*_*die 6

您可以执行以下操作:

$('#form-id').submit(function(e) { //Add event listener on form and not on btn click
  if ($('#firstname').val().trim() === '') { //Check if empty string
    $("#firstname").attr('placeholder', "first name can't be empty"); //Change attribute
    $("#firstname").val(''); //Remove the value so that youll see the new attribute
    $("#firstname").addClass('red'); //Add a class so that placeholder will be red.
    e.preventDefault(); //Prevent the form on sending
  }
});
Run Code Online (Sandbox Code Playgroud)
.red::placeholder { /* Chrome, Firefox, Opera, Safari 10.1+ */
   color: red;
   opacity: 1; /* Firefox */
}

.red:-ms-input-placeholder { /* Internet Explorer 10-11 */
   color: red;
}

.red::-ms-input-placeholder { /* Microsoft Edge */
   color: red;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id='form-id'>
  <input type="text" name="firstname" id="firstname" placeholder="First name">
  <input type="submit" value="Submit">
</form>
Run Code Online (Sandbox Code Playgroud)