标签:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Document</title>
<style>
.tab ul li{
float: left;
height: 40px;
line-height: 40px;
background-color: red;
padding: 0 3px;
list-style: none;
}
.tab ul li:hover{
/*background-color: yellow;*/
}
.tab div {
width: 300px;
height: 100px;
background-color: green;
display: none;
position: absolute;
margin-top: 30px;
margin-left: 20px;
/*这一点也很重要,脱离relative使用absolute,效果更好*/
}
.tab .active{
display: block;
}
</style>
</head>
<body>
<div class="tab">
<ul>
<li>名字</li>
<li>年龄</li>
<li>大小</li>
</ul>
<div class="active">111</div>
<div>222</div>
<div>333</div>
</div>
<script>
var lists = document.getElementsByTagName(‘li‘);
var i = 0;
var tab = document.querySelector(‘.tab‘);
var divs = tab.getElementsByTagName(‘div‘);
// for循环开始
for(i = 0;i< lists.length;i++){
lists[i].index = i; //这一步,因为lists[0]类似的这个东西是不变得,把即时的变量i 保存起来,保存在每个li的属性中
lists[i].onmouseover = function(){ //因为不是立即调用的,所以函数里面的i都会变成最后的值。
// this.backgroundColor = ‘grey‘; //知道哪里错了吗???还是css属性的js语法不熟
// console.log(i);回调函数中不要出现i,因为不是立即调用的,打印的都是3
console.log(this.index);
this.style.backgroundColor = ‘grey‘
// console.log(this);
//把所有被展示内容的class清空
for(var j=0;j<divs.length;j++){
divs[j].className = ‘‘
}
//给当前需要展示的div加上class
divs[this.index].className = ‘active‘
}
lists[i].onmouseout = function(){
this.style.backgroundColor = ‘red‘;
}
}
// for循环结束
</script>
</body>
</html>
要点:回调函数不允许出现for循环的i,因为js只有函数级作用域。
解决方案: 以下代码块内容替代上面js中的for循环
for(i = 0;i< lists.length;i++){
lists[i].index = i;
lists[i].onmouseover = function(){
console.log(this.index);
this.style.backgroundColor = ‘grey‘
for(var j=0;j<divs.length;j++){
divs[j].className = ‘‘
}
divs[this.index].className = ‘active‘
}
lists[i].onmouseout = function(){
this.style.backgroundColor = ‘red‘;
}
}
for(i = 0;i< lists.length;i++){
(function(i){
lists[i].onmouseover = function(){
console.log(i);
this.style.backgroundColor = ‘grey‘
for(var j=0;j<divs.length;j++){
divs[j].className = ‘‘
}
//给当前需要展示的div加上class
divs[i].className = ‘active‘
}
lists[i].onmouseout = function(){
this.style.backgroundColor = ‘red‘;
}
})(i);
}
let 创建块级作用域 ,
for(let i = 0;i< lists.length;i++){
lists[i].onmouseover = function(){
console.log(i);
this.style.backgroundColor = ‘grey‘
for(var j=0;j<divs.length;j++){
divs[j].className = ‘‘
}
//给当前需要展示的div加上class
divs[i].className = ‘active‘
}
lists[i].onmouseout = function(){
this.style.backgroundColor = ‘red‘;
}
}
标签:
原文地址:http://www.cnblogs.com/nostic/p/5901847.html