理解JavaScript表单的基础知识(2)

blur: 当前字段失去焦点时触发;
change:input元素和textarea元素,在它们失去焦点且value值改变时触发;select元素在其选项改变时触发(不失去焦点也会触发);
focus:当前字段获得焦点时触发;
如:

var form = document.forms["myForm"]; var firstName = form.elements["firstName"]; firstName.addEventListener("focus", handler); firstName.addEventListener("blur", handler); firstName.addEventListener("change", handler); function handler() { switch (event.type) { case "focus": if (firstName.style.backgroundColor !== "red") { firstName.style.backgroundColor = "yellow"; }; break; case "blur": if (event.target.value.length < 1) { firstName.style.backgroundColor = "red"; } else { firstName.style.backgroundColor = ""; }; break; case "change": if (event.target.value.length < 1) { firstName.style.backgroundColor = "red"; } else { firstName.style.backgroundColor = ""; }; break; } }

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wgwgzj.html