模拟hover
鼠标悬浮在哪个button上,该button变成绿色背景。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
button{
width:100px;
height:25px;
}
button.active{
background-color:green;
}
</style>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<button>按钮5</button>
<script>
oBtns = document.getElementsByTagName('button');
window.onload = function(){
for(i=0; i < oBtns.length; i++){
oBtns[i].onmouseover = function(){
// 重要:排他思想,先把所有的按钮的className设置为空,然后把(this)当前这个按钮的className设置为active
for(j=0; j<oBtns.length; j++){
this.className = '';
}
this.className = 'active';
}
oBtns[i].onmouseout = function(){
this.className = '';
}
}
}
</script>
</body>
</html>
tab栏选项
需求:鼠标放在上面li标签上,li标签变色(添加类),对应下面p也显示出来(添加类)。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<style>
*{
margin:0;
padding:0;
}
#tab{
width:300px;
background-color:red;
margin: 20px auto;
}
#tab ul{
list-style:none;
overflow:hidden;
}
#tab ul li{
width:100px;
height:49px;
float:left;
background-color:#ccc;
text-align:center;
line-height:49px;
}
#tab ul li a{
color:black;
display:block;
width:100%;
height:100%;
text-decoration:none;
}
#tab p{
display:none;
height:200px;
text-align:center;
line-height:200px;
background-color:red;
}
#tab p.active{
display:block;
}
#tab ul li.active{
background-color:red;
}
</style>
</head>
<body>
<div id="tab">
<ul>
<li class="active"><a href="javascript:void(0)">首页</a></li>
<li><a href="javascript:void(0)">新闻</a></li>
<li><a href="javascript:void(0)">照片</a></li>
</ul>
<p class="active">首页内容</p>
<p>新闻内容</p>
<p>照片内容</p>
</div>
<script>
//1. 点亮li
var tabLi = document.getElementsByTagName('li');
var oP = document.getElementsByTagName('p');
for(i=0;i<tabLi.length;i++){
// 将for循环的i数值保存到tabLi的属性中,解决i=3的问题。
tabLi[i].index = i;
tabLi[i].onclick = function(){
for(j=0; j<tabLi.length;j++){
tabLi[j].className='';
oP[j].className='';
}
this.className = 'active';
/*
// Cannot set property 'className' of undefined,因为此时i的值是3.
// 变量提升,是浏览器内部的处理,将var i=0,提升为var a; 在for中a=0;即将for循环的i提升到了for循环外面去声明。
// for 循环和点击事件 谁快?i是全局作用域,当点击时,i的值已经成为了3.
oP[i].className = 'active';
*/
oP[this.index].className = 'active';
}
}
</script>
</body>
</html>
效果:
可将var的变量声明修改为let声明来解决变量提升问题,变为局部变量。