我有一个视图输入字段。只需填写第一个输入字段。其他字段可能为空。当用户将第一个输入字段保留为空并按下提交按钮时,boxShadow-color和bordercolor将为红色。我想要的是,当用户再次按下输入框时,边框颜色和boxShadow颜色又回到了他们所在的位置。 (表单控件类的焦点颜色,浅蓝色)。
这是我的一些代码。在if语句中,当输入字段为空时,我将颜色更改为红色。我试图制作一个新的if语句,例如:if(输入字段focus = true),然后恢复正常。也使用onclick尝试过此方法,但问题是仅在按下提交按钮时才会触发。我需要手势之类的东西。一直在看着它。
ok: {
label: "Submit",
className: 'btn-success',
callback: function() {
var inputDossierTitle = document.getElementById("inputDossierTitle");
var inputDossierSubTitle = document.getElementById("inputDossierSubTitle").value;
var inputDossierSummary = document.getElementById("inputDossierSummary").value;
var selectDossierPrivacySettings = document.getElementById("selectDossierPrivacySettings").value;
const isEmpty = str => !str.trim().length;
if (isEmpty(inputDossierTitle.value)) {
inputDossierTitle.style.borderColor = "red";
inputDossierTitle.style.boxShadow = "0 0 0 0.2rem rgba(255, 0, 0, 0.36)";
return false;
} else {
$.ajax({
url : '/create-dossier',
type: "POST",
data: {title: inputDossierTitle.value, sub_title: inputDossierSubTitle, summary: inputDossierSummary, PrivacySettings: selectDossierPrivacySettings},
success : function () {
$('.filtr-container').remove();
new Dossier();
}
});
}
}
}
您可以将错误样式基于CSS类名,即。 is-invalid
(...) .is-invalid {
border-color: red;
box-shadow: 0 0 0 0.2rem rgba(255, 0, 0, 0.36);
}
然后像这样使用它:
if (isEmpty(inputDossierTitle.value)) {
inputDossierTitle.classList.add('is-invalid');
return false;
}
// just a note, you dont need to have else {} here since you are returning inside of if statement
并侦听指定的事件类型,以删除该类:
如果输入焦点足够:
inputDossierTitle.addEventListener('focus', (event) => {
inputDossierTitle.classList.remove('is-invalid');
})
或者在输入不再为空时删除错误:
inputDossierTitle.addEventListener('input', (event) => {
if (event.target.value.trim().length) { // or use your isEmpty function
inputDossierTitle.classList.remove('is-invalid');
}
})
尝试与blur
事件一起玩