H5阻止默认气泡,添加错误信息
Posted island1994
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了H5阻止默认气泡,添加错误信息相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <style> .oneline { line-height: 1.5; margin: 10px auto; } .oneline label { width: 100px; text-indent: 15px; font-size: 14px; font-family: "Microsoft Yahei"; display: inline-block; } .oneline .sinput { width: 60%; height: 30px; border-radius: 6px; border: 1px solid #e2e2e2; } .oneline input[type="submit"] { margin-left: 20px; width: 80px; height: 30px; border: 0; background-color: #5899d0; color: #fff; font-size: 14px; border-radius: 6px; } .error-messages { color: red; } </style> <body> <form id="forms"> <div class="oneline"> <label for="name">用户名:</label> <input id="name" class="sinput" name="name" type="text" required> </div> <div class="oneline"> <label for="email">Email:</label> <input id="email" class="sinput" name="email" type="email" required> </div> <div class="oneline"> <input type="submit" id="submits" value="提交"> </div> </form> <script> function replaceValidationUI(form) { form.addEventListener("invalid", function(event) { event.preventDefault(); }, true); form.addEventListener("submit", function(event) { if (!this.checkValidity()) { event.preventDefault(); } },true); var submitBtn=document.getElementById("submits"); submitBtn.addEventListener("click",function(){ var invalidFields=form.querySelectorAll(":invalid"), errorMessages=form.querySelectorAll(".error-messages"), parent; for(var i=0;i<errorMessages.length;i++){ errorMessages[i].parentNode.removeChild(errorMessages[i]); } for(var i=0;i<invalidFields.length;i++){ parent=invalidFields[i].parentNode; parent.insertAdjacentHTML("beforeEnd","<div class=‘error-messages‘>"+invalidFields[i].validationMessage+"</div>"); } if (invalidFields.length > 0) { invalidFields[0].focus(); } }) } var form = document.getElementById("forms"); replaceValidationUI(form); </script> </body> </html>
以上是关于H5阻止默认气泡,添加错误信息的主要内容,如果未能解决你的问题,请参考以下文章