【问题标题】:MouseLeave event not firing for anchor and other inline elements未针对锚点和其他内联元素触发 MouseLeave 事件
【发布时间】:2019-07-15 14:58:06
【问题描述】:

我有一个 codepen 的链接,这个问题在 Chrome 中最能观察到:

https://codepen.io/pkroupoderov/pen/jdRowv

当用户将鼠标快速移动到多个图像上时,有时不会触发 mouseLeave 事件,这意味着某些图像仍会应用灰度过滤器。如何解决?如果我使用 div 而不是锚元素,它工作得很好。我应该稍微更改标记还是将某些样式应用于锚元素?

我正在尝试在用户将鼠标悬停在图像上时在图像上创建叠加效果,就像在 Instagram 上一样。稍后我会将内容添加到叠加层中,我只需要解决 mouseLeave 事件问题。 CSS 伪样式不起作用,因为叠加层需要在其中包含内容。

const imageUrls = [
  'https://farm8.staticflickr.com/7909/33089338628_052e9e2149_z.jpg',
  'https://farm8.staticflickr.com/7894/46240285474_81642cbd37_z.jpg',
  'https://farm8.staticflickr.com/7840/32023738937_17d3cec52f_z.jpg',
  'https://farm8.staticflickr.com/7815/33089272548_fbd18ac39f_z.jpg',
  'https://farm5.staticflickr.com/4840/40000181463_6eab94e877_z.jpg',
  'https://farm8.staticflickr.com/7906/46912640552_4a7c36da63_z.jpg',
  'https://farm5.staticflickr.com/4897/46912634852_93440c416a_z.jpg',
  'https://farm5.staticflickr.com/4832/46964511231_6da8ef5ed0_z.jpg'
]

class Image extends React.Component {
  state = {hovering: false} 

  handleHover = () => {
    this.setState({hovering: true})
  }
  handleLeave = () => {
    this.setState({hovering: false})
  }

  render() {
    if (!this.state.hovering) {
      return (
        <div onMouseOver={this.handleHover}>
          <img src={this.props.url} alt='' />
        </div>
      )
    } else {
      return ( // works fine when using <div> tag instead of <a> or <span>
        <a href="#" style={{display: 'block'}} onMouseLeave={this.handleLeave}>
          <img style={{filter: 'opacity(20%)'}} src={this.props.url} alt='' />
        </a>  
      )
    }
  }
}

const Images = () => {
  return (
    <div className="gallery">  
      {imageUrls.map((image, i) => {
        return <Image key={i} url={image} />
      })}
    </div>
  )
}

ReactDOM.render(<Images />, document.getElementById('app'))

【问题讨论】:

    标签: html css reactjs


    【解决方案1】:

    我的猜测是你的鼠标在它能够将新元素重新渲染到页面之前离开了组件。我建议不要有条件地将不同的元素渲染到组件中,而只是使用条件在标签内以不同的方式渲染样式。

    我的解决方案是将 Image 组件中的渲染函数更改为类似的内容

    render() {
      return ( // works fine when using <div> tag instead of <a> or <span>
        <a href="#" style={{display: 'block'}} onMouseLeave={this.handleLeave} onMouseOver={this.handleHover}>
          <img style={{filter: this.state.hovering ? 'opacity(20%)' : 'none'}} src={this.props.url} alt='' />
        </a>  
      )
    }
    

    https://codepen.io/anon/pen/GzaGgq

    【讨论】:

    • 太棒了,它就像一个魅力。通过使用这个概念,我能够实现我的最终目标。
    猜你喜欢
    • 2019-07-14
    • 1970-01-01
    • 1970-01-01
    • 2012-07-11
    • 1970-01-01
    • 2014-08-18
    • 2012-10-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多