<!DOCTYPE html>
<html lang="en">
<head>
? ? <meta charset="UTF-8">
? ? <meta name="viewport" content="width=device-width, initial-scale=1.0">
? ? <meta http-equiv="X-UA-Compatible" content="ie=edge">
? ? <title>Document</title>
? ? <style>
? ? ? ? .active {
? ? ? ? ? ? background: red;
? ? ? ? }
? ? ? ? div {
? ? ? ? ? ? font: 200px "宋體";
? ? ? ? ? ? display: none;
? ? ? ? }
? ? ? ? .show {
? ? ? ? ? ? display: block;
? ? ? ? }
? ? </style>
</head>
<body>
<button class="btn active">按鈕1</button>?
<button class="btn">按鈕2</button>?
<button class="btn">按鈕3</button>?
<button class="btn">按鈕4</button>?
<div class="show">內(nèi)容1</div>
<div>內(nèi)容2</div>
<div>內(nèi)容3</div>
<div>內(nèi)容4</div>
<script>
var btns = document.querySelectorAll(".btn");
var inners = document.querySelectorAll("div");
var now = 0; // 記錄選中的是哪一個(gè)
/*
? ? 點(diǎn)中當(dāng)前讓之前選中的纲仍,取消選中哭尝,然后給當(dāng)前選中
*/
for(var i = 0; i < btns.length; i++){
? ? // 如果需要知道當(dāng)前操作的是這組中的第幾個(gè)一定記得加索引
? btns[i].index = i;
? btns[i].onmouseover = function(){
? ? ? // 清除現(xiàn)在選中的
? ? ? ? btns[now].classList.remove("active");
? ? ? ? inners[now].classList.remove("show");
? ? ? ? // 給當(dāng)前加上選中效果
? ? ? ? this.classList.add("active");
? ? ? ? //console.log(this.index);
? ? ? ? inners[this.index].classList.add("show");
? ? ? ? //同步當(dāng)前選中的是第幾個(gè)
? ? ? ? now = this.index;
? };?
}
</script>
</body>
</html>