效果图:
App.jsx
import React, {Component} from 'react'
import style from './index.module.less'
export default class App extends Component {state = { width: 0, left: 0}
enter = (event) => {const {clientWidth, offsetLeft} = event.target
this.setState({
width: clientWidth,
left: offsetLeft
})
}
leave = () => {this.setState(() =>({width: 0}) )
}
render () {const { width, left} = this.state
return (
<>
<div className={style.header}>
<ul ref="ul" onMouseLeave={this.leave} >
<li onMouseEnter={this.enter}> 首页 </li>
<li onMouseEnter={this.enter}> 导航一 </li>
<li onMouseEnter={this.enter}> 导航二 </li>
<li onMouseEnter={this.enter}> 导航三 </li>
<li onMouseEnter={this.enter}> 导航四 </li>
</ul>
<div className={style.line} style={{width: width, left: left, height: '2px'}}></div>
</div>
</>
)
}
}
App.module.less
.header {
position: relative;
padding-left: 50px;
ul {
display: flex;
margin: 0;
padding: 0;
li {
list-style: none;
padding: 10px;
cursor: pointer;
font-weight: 500;
&:hover{color: orangered}
}
}
.line {
position: absolute;
bottom: 0;
transition: .3s cubic-bezier(.4,0,.2,1);
background-color: #c7000b;
}
}