对于悬浮菜单,主要是借助html标签的事件机制,或者hover来实现,先看下效果图:
1.先说下利用事件机制做法:
在事件机制中,主要利用鼠标的一些事件来监听,具体如下:
可以利用onMouSEOver(鼠标进入),onMouseLeave (鼠标离开)来监听鼠标的变化
class UserMenu extends React.Component{ constructor(props){ super(props),this.state={ modalIsOpen:'none',atUserItems:false,} this.contentBtn=this.contentBtn.bind(this),this.programBtn=this.programBtn.bind(this),this.handleMouSEOver = this.handleMouSEOver.bind(this); this.handleMouSEOut = this.handleMouSEOut.bind(this); this.userCenter = this.userCenter.bind(this); this.handleMouseUserOver = this.handleMouseUserOver.bind(this); } contentBtn(){ this.context.router.history.push("/details"); } programBtn(){ this.context.router.history.push("/gui"); } handleMouSEOver(e){ this.setState({ modalIsOpen: 'block',}) } handleMouSEOut(){ this.setState({ modalIsOpen: 'none',}) } handleMouseUserOver(e){ this.setState({ modalIsOpen: 'block',}) } userCenter(){ this.setState({ modalIsOpen: 'none',}) } render(){ const {username} = this.props; return( <div className={styles.body} > <div className={styles.uname} onMouSEOver={this.handleMouSEOver} onMouseLeave={this.handleMouSEOut} >{username}</div> <div className={styles.menus} style={{display:this.state.modalIsOpen}} onMouSEOver={this.handleMouseUserOver} onMouseLeave={this.handleMouSEOut} > <ul className={styles.ul}> <li className={styles.li} onClick={this.userCenter}>个人中心</li> <li className={styles.li} >账号设置</li> <li className={styles.li} >注销</li> </ul> </div> </div> ) } } UserMenu.contextTypes = { router: PropTypes.object.isrequired }; export default UserMenu
.body{ position:relative } .menus{ display:none; position:absolute; right: 0; z-index:999; } .uname{ color: white; margin-left: 5px; margin-right: 10px; cursor: pointer; padding-top: 25px; padding-bottom: 20px; padding-left: 5px; } .uname:hover{ color: darkorange; } .ul{ width: 120px; background-color: #fff; padding: 10px; border-radius: 8px; -webkit-Box-shadow: 0 5px 10px 0 rgba(12,40,46,0.20); Box-shadow: 0 5px 10px 0 rgba(12,0.20); } .li{ list-style: none; height: 40px; display: list-item; cursor: pointer; } .li:hover{ color: darkorange; }2.如果通过hover判断,需在css中加入 父类:hover .子类{} ,这个样式,然后在其中通过控制display来控制显示与否,
如父组件样式名为A,子组件样式名为B即需这样写: A:hover .B{display:'block'},来控制