console
const buttons = document.querySelectorAll('.button');
const underline = document.querySelector('.underline');
buttons.forEach(button => {
button.addEventListener('mouseover', function() {
const rect = button.getBoundingClientRect();
underline.style.width = `${rect.width}px`;
underline.style.transform = `translateX(${rect.left}px)`;
});
});
<div class="buttons">
<button class="button">按钮1</button>
<button class="button">按钮2</button>
<button class="button">按钮3</button>
<button class="button">按钮4</button>
<div class="underline"></div>
</div>
.buttons {
display: flex;
flex-direction: row;
position: relative;
}
.button {
margin: 0 10px;
padding: 5px 10px;
cursor: pointer;
}
.underline {
position: absolute;
left: 0;
bottom: 0;
height: 2px;
background-color: blue;
transition: transform 0.3s;
}