js焦点事件

时间:6年前   阅读:4151

  焦点事件会在页面获得或失去焦点时触发。利用这些事件并与document.hasFocus()方法及 document.activeElement属性配合,可以知晓用户在页面上的行踪

  焦点事件共包括下面4个

blur

  blur事件在元素失去焦点时触发。这个事件不会冒泡

focus

  focus事件在元素获得焦点时触发。这个事件不会冒泡

focusin

  focusin事件在元素获得焦点时触发。这个事件与focus事件等价,但它冒泡

focusout

  focusour事件在元素失去焦点时触发。这个事件与blur事件等价,但它冒泡

  [注意]关于focusin和focusout事件,除了IE浏览器支持DOM0级事件处理程序,其他浏览器都只支持DOM2级事件处理程序

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
</head>
<body>
<div id="box"style="display:inline-block;padding:25px;background-color:lightgreen;">
    <div id="boxIn" style="height: 50px;width: 50px;background-color:pink;">123</div>
</div>
<button id="btn1">内容为123的div元素获取焦点</button>
<button id="btn2">内容为123的div元素失去焦点</button>
<button id="reset">还原</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>
</body>
</html>

由运行结果可知,focusin事件可冒泡;而blur事件不可冒泡

二、焦点事件常用于表单展示及验证

  比如,获取焦点时,修改背景颜色;失去焦点时,还原背景颜色并验证

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
</head>
<body>
<div id="box">
    <input id="input1" type="text" placeholder="只可以输入数字">
    <input id="input2" type="text" placeholder="只可以输入汉字">    
    <span id="tips"></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>
</body>
</html>

本站声明:网站内容来源于网络,如有侵权,请联系我们https://www.qiquanji.com,我们将及时处理。

微信扫码关注

更新实时通知

上一篇:4月29日50ETF期权行情分析

下一篇:K线图中的MA5、MA10、MA20、MA30、MA60有什么含义?

网友评论

请先 登录 再评论,若不是会员请先 注册