【问题标题】:Hovering and playing video悬停和播放视频
【发布时间】:2018-10-01 17:26:13
【问题描述】:

我正在尝试制作一个可以在悬停时播放的视频库......并且仅在悬停时播放。但出于某种原因,有时即使鼠标退出视频也会继续播放。

我正在使用 aurelia 的 mouseover.delegate="hoverVideo($index)"mouseout.delegate="hideVideo($index)" 来启动播放。

  hoverVideo = index => {
    let id = "#video" + "-" + index.toString();

    let isPlaying =
      $(id).get(0).currentTime > 0 &&
      !$(id).get(0).paused &&
      !$(id).get(0).ended &&
      $(id).get(0).readyState > 2;

    if (!isPlaying) {
      $(id)
        .get(0)
        .play();
    }
  };
  hideVideo = index => {
    let id = "#video" + "-" + index.toString();
    let isPlaying =
    $(id).get(0).currentTime > 0 &&
    !$(id).get(0).paused &&
    !$(id).get(0).ended &&
    $(id).get(0).readyState > 2;

    if (isPlaying) {
    $(id)
      .get(0)
      .pause();
    }
  };

如何让视频在鼠标退出时始终停止播放?

【问题讨论】:

    标签: hover html5-video aurelia jquery-hover


    【解决方案1】:

    尝试使用mouseenter.triggermouseleave.trigger。触发事件侦听器直接附加到 html 元素(而不是像委托那样在 body 标签上),并且可以根据您的页面年龄有多大的响应。

    此外,您可以尝试将(部分)事件处理程序逻辑包装在事件回调中的 TaskQueue.queueMicroTask 调用中。这会在下一个requestAnimationFrame 执行您的代码,并确保元素已准备好响应您的更改。

    也许将元素存储在一个变量中,这样您就不需要多次查询 DOM。

    例子:

    hideVideo = index => {
      const id = "#video" + "-" + index.toString();
      const video = $(id).get(0);
      const isPlaying = video.currentTime > 0
        && !video.paused 
        && !video.ended
        && video.readyState > 2;
    
      if (isPlaying) {
        // if the element is still somehow busy during mouseleave
        this.taskQueue.queueMicroTask(() => {
          video.pause();
        });
      }
    }
    

    或者:

    hideVideo = index => {
      const id = "#video" + "-" + index.toString();
      const video = $(id).get(0);
    
      // if the state isn't always up-to-date in time
      this.taskQueue.queueMicroTask(() => {
        const isPlaying = video.currentTime > 0
          && !video.paused 
          && !video.ended
          && video.readyState > 2;
    
        if (isPlaying) {
          video.pause();
        }
      });
    }
    

    如果这仍然不起作用,则视频的状态可能不是您所期望的。像pause() 这样的操作应该是幂等的,所以你可以尝试完全跳过isPlaying 检查。

    【讨论】:

    • 由于mouseenter 没有冒泡,您可以调用所有视频在父元素自己的mouseenter 元素上暂停。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-11-27
    • 1970-01-01
    • 2020-07-22
    • 2015-03-11
    • 2020-04-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多