首先,先来一张效果图:
其次,总结一下需要注意的地方:
- 整个代码都需要写在 window.onload 事件中,因为页面加载完毕 ,才能拿到html元素,否则会报错;
- 事件注册以后,在里面拿不到 lis[i] 和 遍历数组的索引,所有在事件函数内只能用 this 或者事件源 event.target;
- 因为原因2,所有需要把菜单的索引存下来,然后到事件注册后取出索引;
- tabIndex是一个对象的内置属性,默认值是-1,表示的是索引;
- 去除所有的当前样式时,只能在onmouseover事件函数里面去再次变量;
- 如果js代码写在body之前,需要将所有代码下载 window.onload (页面加载完成之后执行)时间里;如果写在body之后,则不需要
最后,上完整代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>滑动菜单</title>
<style type="text/css">
#outbox{
width: 500px;
margin: 0 auto;
background: #eee;
box-sizing: border-box;
padding: 10px 25px;
}
ul,li{
list-style: none;
padding: 0px;
margin: 0px;
}
li{
float: left;
width: 150px;
height: 30px;
line-height: 30px;
text-align: center;
background: #bbb;
color: white;
}
.liActive{
background: white;
color: red;
}
.con{
height: 100px;
margin-top: 15px;
text-align: center;
}
</style>
<script type="text/javascript">
//页面加载完毕 ,才能拿到html元素,否则会报错
window.onload = function (){
var lis = document.getElementById("title").getElementsByTagName("li");
var cons = document.getElementById("content").getElementsByClassName("con");
//鼠标滑入onmouseover
//批量注册事件
for (var i = 0; i < lis.length; i++) {
var currentLi = lis[i];
//先把菜单的索引存下来,然后到事件注册后取出索引
//tabIndex是一个对象的内置属性,默认值是-1,表示的是索引
currentLi.tabIndex = i;
//1.移到谁上面谁就显示为当前class="current"
//把所有的当前样式都去掉,只能在onmouseover事件里面去清除
lis[i].onmouseover = function (){
for (var j = 0; j < lis.length; j++) {
lis[j].className = '';
cons[j].style.display = 'none';
}
//保留当前移上去的样式,只能用this,事件注册里面拿不到 lis[i] 和 遍历数组的索引
this.className = 'liActive';
cons[this.tabIndex].style.display = 'block';
}
}
}
</script>
</head>
<body>
<div id="outbox">
<ul id="title">
<li class="liActive">北 京</li>
<li>上 海</li>
<li>深 圳</li>
</ul>
<div style="clear: both;"></div>
<div id="content">
<div class="con" style="background: #fcc;">
内容111
</div>
<div class="con" style="background: #cfc;display: none;">
内容222
</div>
<div class="con" style="background: #ccf;display: none;">
内容333
</div>
</div>
</div>
</body>
</html>
文章仅为本人学习过程的一个记录,仅供参考,如有问题,欢迎指出!