http://www.alistapart.com/articles/forward-thinking-form-validation/
フィールドは一度無効になったことを示すだけなので
フォーカス擬似クラスを使用して無効なスタイリングをトリガーします。
(当然ながら、必要なすべてのフィールドを最初から無効とフラグを立てる
設計上の選択肢が貧弱です)。
このロジックに従って、あなたのコードは次のようになります...
<script>
document.addEventListener('DOMContentLoaded', function() {
var required = document.querySelectorAll('input:required');
for (var i = 0; i < required.length; ++i) {
(function(elem) {
function removeClass(name) {
if (elem.classList) elem.classList.remove(name);
else
elem.className = elem.className.replace(
RegExp('(^|\\s)\\s*' + name + '(?:\\s+|$)'),
function (match, leading) {return leading;}
);
}
function addClass(name) {
removeClass(name);
if (elem.classList) elem.classList.add(name);
else elem.className += ' ' + name;
}
//If you require a class, and you use JS to add it, you end up
//not showing pink at all if JS is disabled.
//One workaround is to have the class on all your elements anyway,
//and remove it when you set up proper validation.
//The main problem with that is that without JS, you see what you're
//already seeing, and stuff looks hideous.
//Unfortunately, you kinda have to pick one or the other.
//Let non-blank elements stay "touched", if they are already,
//so other stuff can make the element :invalid if need be
if (elem.value == '') addClass('touched');
elem.addEventListener('blur', function() {
addClass('touched');
});
//Oh, and when the form submits, they need to know about everything
if (elem.form) {
elem.form.addEventListener('submit', function() {
addClass('touched');
});
};
})(required[i]);
}
});
</script>
もちろん、(a) DOMContentLoaded
は比較的新しく、IE8が出てきたときには標準ではなかったので、IE8では attachEvent addEventListener
ではなく、:required
を気にするつもりはありません.HTMLを技術的にサポートしていないので5。