<divstyle="display:inline-block;padding:25px;background-color:lightgreen;"> <div>123</div> </div> <button>内容为123的div元素获取焦点</button> <button>内容为123的div元素失去焦点</button> <button>还原</button> <script> reset.onclick = function(){history.go();} //focus()方法 btn1.onclick = function(){ boxIn.tabIndex= -1; boxIn.focus(); } //blur()方法 btn2.onclick = function(){ boxIn.blur(); } //focusin事件 if(boxIn.addEventListener){ boxIn.addEventListener('focusin',handler) }else{ boxIn.onfocusin = handler; } function handler(){ this.style.backgroundColor ='lightblue'; } if(box.addEventListener){ box.addEventListener('focusin',handler) }else{ box.onfocusin = handler; } //blur事件 function fnBlur(){ this.style.backgroundColor = 'orange'; } boxIn.onblur = fnBlur; box.onblur = fnBlur; </script>
由运行结果可知,focusin事件可冒泡;而blur事件不可冒泡
焦点事件常用于表单展示及验证
比如,获取焦点时,修改背景颜色;失去焦点时,还原背景颜色并验证
<div> <input type="text" placeholder="只可以输入数字"> <input type="text" placeholder="只可以输入汉字"> <span></span> </div> <script> if(box.addEventListener){ box.addEventListener('focusin',fnIn); box.addEventListener('focusout',fnOut); }else{ box.onfocusin = fnIn; box.onfocusout = fnOut; } function fnIn(e){ e = e || event; var target = e.target || e.srcElement; target.style.backgroundColor = 'lightgreen'; } function fnOut(e){ e = e || event; var target = e.target || e.srcElement; target.style.backgroundColor = 'initial'; //如果是验证数字的文本框 if(target === input1){ if(!/^\d*$/.test(target.value.trim())){ target.focus(); tips.innerHTML = '只能输入数字,请重新输入' setTimeout(function(){ tips.innerHTML = '' },500); } } //如果是验证汉字的文本框 if(target === input2){ if(!/^[\u4e00-\u9fa5]*$/.test(target.value.trim())){ target.focus(); tips.innerHTML = '只能输入汉字,请重新输入' setTimeout(function(){ tips.innerHTML = '' },500); } } } </script>
总结
以上就是为大家总结Javascript中焦点管理的全部内容,这篇文章介绍的很详细,对大家的学习和工作具有一定的参考借鉴价值,如果有疑问大家可以留言交流。
您可能感兴趣的文章: