实现思路:
清除全部元素的class
,然后只给当前被点击的元素加上class
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
#list {
display: flex;
}
#list>p {
width: 100px;
height: 28px;
text-align: center;
line-height: 28px;
background: deepskyblue;
color: white;
margin-left: 20px;
}
#list>.active {
width: 100px;
height: 28px;
background: black;
color: white;
}
</style>
</head>
<body>
<div id="list">
<p>内容1</p>
<p>内容2</p>
<p>内容3</p>
<p>内容4</p>
<p>内容5</p>
<p>内容6</p>
</div>
</body>
<script>
(function() {
var list = document.getElementById('list');
var p = list.getElementsByTagName('p');
for (var i = 0; i < p.length; i++) {
p[i].onclick = function() {
for (var i = 0; i < p.length; i++) {
p[i].className = '';
}
this.className = 'active';
}
}
})();
</script>
</html>
这里为了不污染全局变量使用了闭包
如果想默认选择一个元素 这里列举第三个吧
<script>
(function() {
var list = document.getElementById('list');
var p = list.getElementsByTagName('p');
p[2].className = 'active'
for (var i = 0; i < p.length; i++) {
p[i].onclick = function() {
for (var i = 0; i < p.length; i++) {
p[i].className = '';
}
this.className = 'active';
}
}
})();
</script>
直接p[2].className = 'active'
效果