主动操作的两个样例
#6.23
一、注册界面(主动获取焦点)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>主动操作样例1:注册界面2-主动获取焦点</title>
<style>
.borderGreen {
border: 2px solid green
}
/*输入正确*/
.colorGreen {
color: green
}
.borderRed {
border: 2px solid red
}
/*输入错误*/
.colorRed {
color: red
}
</style>
</head>
<body>
<p>
<span>用户名:</span>
<input type="text" class="userName"/>
<span class="userNameSpan"></span>
</p>
<button>提交</button>
<script>
var input = document.querySelector('input');
var userNameSpan = document.querySelector('.userNameSpan');
var but = document.querySelector('button');
//主动聚焦:让input主动获取焦点 input.focus();
input.onblur = function () {
if (this.value.length == 11) {
this.className = 'borderGreen';
userNameSpan.className = 'colorGreen';
userNameSpan.innerHTML = '正确';
} else {
this.className = 'borderRed';
userNameSpan.className = 'colorRed';
userNameSpan.innerHTML = '手机号有误';
}
}
but.onclick = function () {
//用于blur事件的判断
input.focus(); //主动聚焦
input.blur(); //失去焦点 进行判断
//将焦点定位于不合法的input当中
input.focus(); //再次主动聚焦回
}
//对了也没啥反应
</script>
</body>
</html>
二、导航栏
<!DOCTYPE html>
<head lang="en">
<html>
<meta charset="UTF-8">
<title>主动操作样例2:导航栏</title>
<style>
ul {
list-style: none;
padding: 0;
}
li {
display: inline-block;
width: 150px;
height: 30px;
text-align: center;
line-height: 30px;
background-color: greenyellow;
cursor: pointer;
}
</style>
</head>
<body>
<ul>
<li><a href="http://www.baidu.com">百度</a></li>
<li><a href="http://www.sina.com">新浪</a></li>
<li><a href="http://www.baidu.com">百度</a></li>
<li><a href="http://www.baidu.com">百度</a></li>
</ul>
<script>
var lis = document.querySelectorAll('li') //全部获取li
for (var i = 0; i < lis.length; i++) {
lis[i].onclick = function () {
this.querySelector('a').click(); //点击li相当于点击a标签
}
}
//感觉其实没啥新内容
</script>
</body>
</html>