<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 submits = document.getElementById('submits');
submits.addEventListener('click',function(event){
var fields = form.querySelectorAll(':invalid'),
error = form.querySelectorAll('.error-messages'),
parent,label;
for(var i = 0;i<error.length;i++){
error[i].parentNode.removeChild(error[i]);
};
for(var m = 0;m < fields.length;m++){
label = form.querySelector('label[for='+ fields[fields.length-m-1].id+']');
parent = form;
parent.insertAdjacentHTML("afterBegin","<div class='error-messages'><ul><li>" + label.innerText + fields[m].validationMessage+"</li></ul></div>");
};
if (fields.length > 0) {
fields[0].focus();
};
})
}
var forms = document.getElementById("forms");
replaceValidationUI(forms);
</script>
</body>
就是 ,有个bug谁能帮我解决下, 我把input type="text" 空着,只输入 type="email" 的内容,邮箱格式错误提示会显示在label for=”name“上,这样就很尴尬。
Stardust1001