描述:当点击链接的时候,自己的标签的背景色进行更换,其他标签进行还原。
效果图:
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>导航栏的练习</title>
<style>
*{
margin: 0;
padding: 0;
}
#list li{
list-style: none;
width: 80px;
height: 30px;
line-height: 30px;
background: #a2a5ff;
text-align: center;
float: left;
margin-left: 5px;
}
#list li.current {
background-color: burlywood;
}
#list li a {
text-decoration: none;
}
</style>
</head>
<body>
<div class="nav">
<ul id="list">
<li class="current"><a href="#">首页</a></li>
<li><a href="javascript:void(0)">论坛</a></li>
<li><a href="javascript:void(0)">博客</a></li>
<li><a href="javascript:void(0)">关于</a></li>
<li><a href="javascript:void(0)">留言</a></li>
<li><a href="javascript:void(0)">帮助</a></li>
<li><a href="javascript:void(0)">友链</a></li>
</ul>
</div>
</body>
</html>
<script>
//方式1,排他思想
var ul = document.getElementById("list");
var liArr = ul.children;
for (var i = 0;i<liArr.length;i++){
var a = liArr[i].firstElementChild || liArr[i].firstChild;
a.onclick = function () {
for (var j = 0; j<liArr.length;j++){
liArr[j].className = "";
}
this.parentNode.className = "current";
}
}
//方式2
/* var ul = document.getElementById("list");
var aArr = ul.getElementsByTagName("a");
for (var i = 0;i<aArr.length;i++){
aArr[i].onclick = function () {
this.parentNode.className = "current";
var otherArr = getAllSiblings(this.parentNode);
for (var j = 0;j<otherArr.length;j++){
otherArr[j].className = "";
}
}
}
/!**
* 获取自己的兄弟节点,并且返回一个数组
* @param ele 元素节点
* @returns {Array} 返回
*!/
function getAllSiblings(ele){
var newArr = [];
var arr = ele.parentNode.children;
for(var i=0;i<arr.length;i++){
if(arr[i]!==ele){
newArr.push(arr[i]);
}
}
return newArr;
}*/
</script>