【问题标题】:Does scrolling bring an element out of focus and trigger onBlur event?滚动是否会使元素失去焦点并触发 onBlur 事件?
【发布时间】:2018-06-12 06:38:16
【问题描述】:

我正在使用 React 创建一个页面,其中嵌入了多个视频。我希望在视频超出视口时暂停视频播放。作为第一直觉,我尝试了视频标签中的onBlur 事件,但我的处理程序没有被调用。我查找了各种链接,发现人们使用 window 的 pageYOffset 属性处理了相同的问题。 我可以使用pageYOffset 做到这一点,但我无法理解为什么当视频移出视口时没有调用onBlur 事件处理程序。

<video ref="vidRef" onBlur = {console.log("Blur called")} onPlay={() => this.hidePlayButton()} onPause={() => this.showPlayButton()} onClick={() => this.showPlayButton()} onEnded={() => this.showPlayButton()}>
          <source type="video/mp4" data-reactid=".0.1.0.0.0" src={this.props.hpVideoSrc}/>
      </video>

在尝试上面的代码 sn-p 时,我可以在控制台上看到输出。但是一旦我像这样用我的处理程序替换了控制台命令,

<video ref="vidRef" onBlur={() => this.handleOnBlur()} onPlay={() => this.hidePlayButton()} onPause={() => this.showPlayButton()} onClick={() => this.showPlayButton()} onEnded={() => this.showPlayButton()}>
          <source type="video/mp4" data-reactid=".0.1.0.0.0" src={this.props.hpVideoSrc}/>
      </video>

它只是没有工作。未调用 onBlur 处理程序。我想知道为视频元素调用onBlur 事件的条件是什么。当我将视频滚动到视野之外时会触发吗?

我可以在这个link 中看到onBlur 的条件。这些是调用事件的唯一条件吗?我是 HTML/CSS 和 JS 的初学者,所以我对事件没有深入的了解。

【问题讨论】:

  • onBlur 通常用于输入字段,因此您应该尝试 onmouseout (w3schools.com/jsref/event_onmouseout.asp),但我建议您添加一个 DOM 事件,用于监控滚动并在每次触发时执行一些检查为了找出样式属性 offsetLeft 和 offsetTop 是否不在视野范围内。
  • 请注意,某些事件可能无法按预期进行。特别是浏览器之间的比较,特别是在 explorer/edge 中。
  • onBlur={this.handleOnBlur()} 这使它工作。您只需要简单地调用该函数。但对我来说,问题是页面加载时触发事件。不是当视频离开视口时
  • @IntrepidBlue 您能否简要介绍一下您是如何使用pageYOffset 完成任务的?

标签: javascript html reactjs dom-events


【解决方案1】:

面对类似的问题,对我来说处理包装器 div 元素上的 onmousedown 事件并防止默认操作起作用。 https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-10-02
    • 2023-01-06
    • 2011-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多