一opacity = 1开始我有一张图片。
opacity = 1
当鼠标进入图像时,更改opacity = 0.5。当鼠标离开图像时,将不透明度改回来。
opacity = 0.5
这是一个代码:
mouseEnter() { console.log('mouse enter') const classname = '.' + this.props.post.code document.querySelector(classname).classList.add('image-hover-opacity') } mouseLeave() { console.log('mouse leave') const classname = '.' + this.props.post.code document.querySelector(classname).classList.remove('image-hover-opacity') } render() { <img src={src} onMouseEnter={::this.mouseEnter} onMouseLeave={::this.mouseLeave} /> }
当鼠标进入和离开图像时,分别触发onMouseEnter和onMouseLeave良好。但是问题是当我在图像中移动鼠标时,会触发onMouseEnter和onMouseLeave。
我也尝试了css解决方案,当我将鼠标悬停在图像上时,更改了opacity属性。但是问题是一样的:当我在图像中移动鼠标时,:hover和not hover被多次触发。
如何解决呢?谢谢
更新 我之前的代码中有一些内容。创建了一个jsfiddle,它可以工作。对不起大家
使用document.querySelector不是一种非常反应的思维方式。您可以尝试以下方法:
document.querySelector
div
img
this.state
constructor() { this.state = { opacity: 1 } } mouseEnter() { console.log('mouse enter') this.setState({opacity: 0.5}) } mouseLeave() { console.log('mouse leave') this.setState({opacity: 1}) } render() { <div style={{opacity: this.state.opacity}}> <img src={src} onMouseEnter={::this.mouseEnter} onMouseLeave={::this.mouseLeave} /> </div> }