<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
button {
margin: 10px;
width: 100px;
height: 40px;
cursor: pointer;
}
.current {
background-color: red;
}
</style>
</head>
<body>
<button>按钮1</button>
<button>按钮2</button>
<button>按钮3</button>
<button>按钮4</button>
<button>按钮5</button>
<script>
//需求:鼠标放到哪个button上,改button变成黄色背景(添加类)
var btnArr = document.getElementsByTagName("button");
//绑定事件
for(var i=0;i<btnArr.length;i++){ //要为每一个按钮绑定事件,所以用到了for循环
btnArr[i].onmouseover = function () {
//【重要】排他思想:先把所有按钮的className设置为空,然后把我(this)这个按钮的className设置为current
//排他思想和for循环连用
for(var j=0;j<btnArr.length;j++){
btnArr[j].className = "";
}
this.className = "current"; //【重要】核心代码
}
}
//鼠标离开current时,还原背景色
for(var i=0;i<btnArr.length;i++){ //要为每一个按钮绑定事件,所以用到了for循环
btnArr[i].onmouseout = function () { //鼠标离开任何一个按钮时,就把按钮的背景色还原
this.className = "";
}
}
</script>
</body>
</html>
鼠标悬停时,current栏变色,这里用到了排他思想:先把所有按钮的className设置为空,然后把我(this)这个按钮的className设置为current,就可以达到变色的效果。核心代码是:
//排他思想:先把所有按钮的className设置为空,然后把我(this)这个按钮的className设置为current
//排他思想和for循环连用
for(var j=0;j<btnArr.length;j++){
btnArr[j].className = "";
}
this.className = "current";
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
padding: 0;
margin: 0;
}
ul{
list-style: none;
}
#tab{
width: 480px;
margin: 20px auto;
border: 1px solid red;
}
ul{
width: 100%;
overflow: hidden;
}
ul li{
float: left;
width: 160px;
height: 60px;
line-height: 60px;
text-align: center;
background-color: #cccccc;
}
ul li a{
text-decoration: none;
color:black;
}
li.active{
background-color: red;
}
p{
display: none;
height: 200px;
text-align: center;
line-height: 200px;
background-color: red;
}
p.active{
display: block;
}
</style>
</head>
<body>
<div id="tab">
<ul>
<li class="active">
<a href="#">首页</a>
</li>
<li>
<a href="#">新闻</a>
</li>
<li>
<a href="#">图片</a>
</li>
</ul>
<p class="active">首页内容</p>
<p>新闻内容</p>
<p>图片内容</p>
</div>
</body>
<script type=&qu