本文介绍了如何将红色边框与必需属性一起添加到输入字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前,如果所需的输入字段为属性为空,它将显示浏览器的默认错误消息。如果我删除此属性,由于我的JavaScript代码,它将在输入字段上显示一个红色边框。如何同时显示两者?



$(form ).submit(function(e){e.preventDefault(); var title = document.getElementById('title'); if(!title.value){title.classList.add('error'); setTimeout(function( ){title.classList.remove('error');},300);}});
  .error {position:relative;动画:摇动.1s线性; animation-iteration-count:3; border:1px solid red;} @ keyframes shake {0%{left:-5px; } 100%{right:-5px; }}  
< script src =https:// ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script><form> < input type =textid =title> < input type =submit>< / form>


解决方案

您可以像这样实现它:

 <$ (函数(e){e.preventDefault(); // ....}); $(form input)。on(invalid,function(event ){$('#title')。addClass('error'); setTimeout(function(){$('#title')。removeClass('error');},500);});  
.error {position:relative;动画:摇动.1s线性; animation-iteration-count:3;边框:1px纯红色; outline:none;} @ keyframes shake {0%{left:-5px; } 100%{right:-5px; }} < script src =https:// ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script><form> < input type =textid =titlerequired> < input type =submit>< / form>

Currently if an input field with the required attribute is empty, it will display the browser's default error message. If I remove this attribute, it will display a red border on the input field because of my JavaScript code. How would I display both at the same time?

$("form").submit(function(e) {
  e.preventDefault();
  var title = document.getElementById('title');
  if (!title.value) {
    title.classList.add('error');
    setTimeout(function() {
      title.classList.remove('error');
    }, 300);
  }
});
.error {
  position: relative;
  animation: shake .1s linear;
  animation-iteration-count: 3;
  border: 1px solid red;
}

@keyframes shake {
  0% {
    left: -5px;
  }
  100% {
    right: -5px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" id="title">
  <input type="submit">
</form>

解决方案

You can implement it like this:

$("form").submit(function(e) {
  e.preventDefault();
  // ....
});

$("form input").on("invalid", function(event) {
  $('#title').addClass('error');
  setTimeout(function() {
    $('#title').removeClass('error');
  }, 500);
});
.error {
  position: relative;
  animation: shake .1s linear;
  animation-iteration-count: 3;
  border: 1px solid red;
  outline: none;
}

@keyframes shake {
  0% {
    left: -5px;
  }
  100% {
    right: -5px;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input type="text" id="title" required>
  <input type="submit">
</form>

这篇关于如何将红色边框与必需属性一起添加到输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-19 05:23