效果展示
CSS / JavaScript 知识点
- box-shadow 属性运用
- 使用 JS 控制 hue-rotate 属性
页面整体布局
<nav>
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Services</a>
<a href="#">Portfolio</a>
<a href="#">Team</a>
<a href="#">Contact</a>
<div id="indicator"></div>
</nav>
实现整体样式
nav a {
position: relative;
color: #999;
text-decoration: none;
font-size: 1.5em;
z-index: 2;
height: 75px;
display: flex;
justify-content: center;
align-items: center;
padding: 0 30px;
transition: 0.5s;
}
nav a.active {
color: #222327;
}
编写菜单激活状态的事件
let marker = document.querySelector("#indicator");
let nav = document.querySelector("nav");
let item = document.querySelectorAll("nav a");
nav.onclick = () => {
marker.classList.toggle("change");
};
function indicator(e) {
marker.style.left = e.offsetLeft + "px";
marker.style.width = e.offsetWidth + "px";
marker.style.display = "block";
// 控制激活状态下的菜单项的hue-rotate属性,从而产生随机颜色的效果
marker.style.filter = "hue-rotate(" + Math.random() * 360 + "deg)";
}
item.forEach((link) => {
link.addEventListener("click", (e) => {
indicator(e.target);
});
});
function addActiveClass() {
item.forEach((i) => {
i.classList.remove("active");
this.classList.add("active");
});
}
item.forEach((i) => {
i.addEventListener("click", addActiveClass);
});
编写导航块样式
#indicator {
position: absolute;
height: 75px;
width: 150px;
background: #29fd53;
z-index: 1;
transition: 0.5s;
}
#indicator::before {
content: "";
position: absolute;
left: -30px;
width: 50px;
height: 15px;
background: #29fd53;
border-radius: 15px;
box-shadow: 15px 30px #29fd53, 5px 60px #29fd53, -15px 15px #222327, -10px
45px #222327;
transition: 0.5s;
}
#indicator::after {
content: "";
position: absolute;
right: -30px;
width: 50px;
height: 15px;
background: #29fd53;
border-radius: 15px;
box-shadow: 5px 30px #29fd53, -15px 60px #29fd53, 15px 15px #222327, 10px 45px
#222327;
transition: 0.5s;
}
#indicator.change::after {
right: -20px;
box-shadow: 10px 30px #29fd53, 20px 60px #29fd53, 15px 15px #222327, 25px 45px
#222327;
}