效果
HTML部分
<body>
<nav>
<div id="nav1">导航1</div>
<div id="nav2">导航2</div>
<div id="nav3">导航3</div>
<span id="underscore"></span>
</nav>
</body>
CSS 部分
* {
user-select: none;
padding: 0;
margin: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
height: 100%;
background-color: #333744;
}
nav {
padding: 20px;
position: relative;
width: 300px;
height: 30px;
margin-top: 50px;
display: flex;
justify-content: space-between;
align-items: center;
}
nav div {
font-size: 18px;
letter-spacing: 2px;
color: aliceblue;
cursor: pointer;
}
nav span {
position: absolute;
bottom: 0;
background-color: aliceblue;
border-radius: 15px;
width: 100%;
height: 3px;
animation: left 0s ease-in-out;
animation-fill-mode: forwards;
}
@keyframes left {
from {
left: 50%;
width: 100%;
}
to {
left: 18px;
width: 17.5%;
}
}
@keyframes center {
from {
left: 0;
width: 100%;
}
to {
left: 123px;
width: 17.5%;
}
}
@keyframes right {
from {
right: 50%;
width: 100%;
}
to {
right: 20px;
width: 17.5%;
}
}
JavaScript 部分
var speed = 0.5
var tweens = [
{ 'animation': `left ${speed}s ease-in-out`, 'animation-fill-mode': 'forwards' },
{ 'animation': `center ${speed}s ease-in-out`, 'animation-fill-mode': 'forwards' },
{ 'animation': `right ${speed}s ease-in-out`, 'animation-fill-mode': 'forwards' },
]
$(document).ready(function () {
var navs = document.querySelectorAll('nav div');
[].forEach.call(navs, (item, index) => {
item.addEventListener("click", function () {
$('#underscore').css(tweens[index])
})
})
})