<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>index</title>
<style>
nav {
--position: 0;
--bgH: 10%;
--bgY: bottom;
--activeBg: '';
position: relative;
margin: 70px auto 0;
width: 582px;
height: 50px;
transition: background-position .4s;
background: linear-gradient(to right, lightskyblue 20%, transparent 0), linear-gradient(#34495e,#34495e);
background-size: 100% var(--bgH), 100% 100%;
background-repeat: no-repeat, no-repeat;
background-position: var(--position) var(--bgY), 0 0;
border-radius: 8px;
font-size: 0;
box-shadow: 0 3px 10px 0 rgba(0, 0, 0, .3);
display: flex;
}
nav a {
color: #fff;
font-size: 20px;
text-decoration: none;
flex: 1;
display: flex;
justify-content: center;
align-items: center;
}
nav a:hover{
background-color: lightblue;
}
nav a.active{
background-color: linear-gradient(var(--activeBg));
background-size: 100% var(--bgH);
}
nav a:first-child{
border-top-left-radius: 8px;
border-bottom-left-radius: 8px;
}
nav a:last-child{
border-top-right-radius: 8px;
border-bottom-right-radius: 8px;
}
</style>
</head>
<body>
<nav>
<a href="#" active>主页</a>
<a href="#">博客</a>
<a href="#">随笔手记</a>
<a href="#">关于此</a>
<a href="#">联系</a>
</nav>
<script>
let nav = document.querySelector('nav');
let navW = nav.offsetWidth;
nav.addEventListener('click', e => {
nav.style.setProperty('--activeBg', '')
let children = Array.from(nav.children)
children.forEach(t => t.classList.remove('active'))
e.target.classList.add('active')
let index = children.indexOf(e.target);
//获取相对位置简便方法?????
let w = navW/5 * index;
nav.style.setProperty('--position', w + "px")
})
nav.addEventListener('transitionend', e => {
nav.style.setProperty('--activeBg', 'lightskyblue')
})
</script>
</body>
</html>
效果地址