案例分析(今天附一张思维导图):
代码展示:html css js 都写在一块了
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
* {
margin: 0;
padding: 0;
}
body {
background-color: #ccc;
}
.bar-nav {
position: relative;
width: 1200px;
height: 40px;
margin: 100px auto;
border: 1px solid black;
}
ul {
height: 40px;
z-index: 999;
}
li {
float: left;
list-style-type: none;
width: 150px;
}
a {
display: block;
text-decoration: none;
width: 150px;
height: 40px;
line-height: 40px;
text-align: center;
color: blue;
}
.bg {
position: absolute;
top: 0;
left: 0;
display: block;
width: 150px;
height: 40px;
background-color: blue;
z-index: -1;
}
.settextColor {
color: #fff;
}
</style>
<script src="js/animate.js"></script>
<script>
window.addEventListener('load', function() {
// 获取元素
var bar_nav = document.querySelector('.bar-nav');
var bg = document.querySelector('.bg');
var lists = bar_nav.querySelectorAll('li');
var alla = document.querySelectorAll('a');
var current = 0; // 记录 当前 被点击的 li 的 坐标值 offsetLeft
var num = 0; // 监听点击了第几个 li
for(var i = 0; i < lists.length; i++) {
var wherenum = 0; // 记录 鼠标进入 当前li 的索引号
lists[i].setAttribute('index', i); // 给 每个 li 加索引号
// 鼠标进入事件
lists[i].addEventListener('mouseenter', function() {
animate(bg, this.offsetLeft); // 添加动画函数
var index = this.getAttribute('index'); // 获取 被鼠标进入的 当前li 的索引号
wherenum = index; // 赋值索引号 给 wherenum
alla[wherenum].className = 'settextColor'; // 鼠标进入 当前li 添加类名
})
// 鼠标离开事件
lists[i].addEventListener('mouseleave', function() {
animate(bg, current); // 添加动画函数
alla[wherenum].className = ''; // 鼠标离开后 清除刚才鼠标进入的 li 的类名
alla[num].className = 'settextColor'; // 鼠标离开后 被点击的那个 当前li 类名不清空
})
// 鼠标点击事件
lists[i].addEventListener('click', function(e) {
var index = this.getAttribute('index'); // 获取 被点击的 当前li 的索引号
if(num == alla.length) { // 如果 num 的值大于 所以有 a 标签的长度 那么num = 0;
num = 0;
}
num ++;
num = index;
current = this.offsetLeft; // 把 点击的 当前li 的坐标赋值给 current
for(var i = 0; i < alla.length; i++) {
alla[i].className = ''; // 清空所有类名 排他思想法
}
alla[num].className = 'settextColor'; // 鼠标点击 当前li 添加类名
})
}
})
</script>
<body>
<div id="bar_nav" class="bar-nav">
<span class="bg"></span>
<ul>
<li><a href="#" class="settextColor">model1</a></li>
<li><a href="#">model2</a></li>
<li><a href="#">model3</a></li>
<li><a href="#">model4</a></li>
<li><a href="#">model5</a></li>
<li><a href="#">model6</a></li>
<li><a href="#">model7</a></li>
<li><a href="#">model8</a></li>
</ul>
</div>
</body>
</html>
效果展示: