netflix视频_像netflix一样的视频暂停播放

netflix视频

This article by no means explains how Netflix has implemented this feature but it’s something that we can easily manage with the awesome intersection observer API and page visibility API.

本文决不解释Netflix如何实现此功能,但是我们可以使用出色的十字路口观察器API和页面可见性API轻松管理它。

Let me tell you what it’s going to be — if you have been to Netflix, they have a main video section at the top on their browse page which starts playing automatically. They autoplay and pause to make the user experience seamless. Two things that they have done commendably well is -

让我告诉您这是怎么回事–如果您去过Netflix,他们的浏览页面顶部会显示一个主要视频部分,该部分会自动开始播放。 它们会自动播放和暂停,以使用户体验无缝。 值得称赞的两件事是:

1. As soon as you scroll past that video preview section, it pauses and resumes when scrolled back up.

1.滚动到该视频预览部分后,它会暂停并在向上滚动时恢复。

2. Video pauses when the user switches to another tab and resumes when you go back to the browse section.

2.视频在用户切换到另一个选项卡时暂停,并在您返回浏览部分时恢复。

First can be achieved by intersection observer API and the second with page visibility API. Let’s look at the implementation below.

第一个可以通过交叉观察器API实现,第二个可以通过页面可见性API实现。 让我们看看下面的实现。

我们正在处理的示例 (Example we are working with)

It’s going to be a simple vanilla JavaScript app where we have a video and some random text. You can see it in the Code Sandbox. Currently it doesn’t achieve the aforementioned features and video continues to play(Please click on the play control to play the video and unmute to hear the audio).

这将是一个简单的原始JavaScript应用程序,其中有一个视频和一些随机文本。 您可以在“代码沙箱”中看到它。 目前,它无法实现上述功能,并且视频仍在继续播放(请单击播放控件以播放视频,然后取消静音以收听音频)。

I had to use video controls here as we cannot autoplay video with audio by default as far as I have researched. Someone please do let me know if this can be achieved though.

我不得不在这里使用视频控件,因为据我研究,默认情况下我们无法自动播放带音频的视频。 请有人告诉我是否可以实现。

交叉口观察者API (Intersection Observer API)

If you are unaware of how this API works, please have a look at one of my previous article which goes deep into its functionality with examples.

如果您不知道此API的工作原理,请查看我以前的一篇文章 ,其中将通过示例深入介绍其功能。

Basically this API provides an easy way to watch and register callbacks to trigger when elements on a page come into view.

基本上,此API提供了一种简单的方法来查看和注册回调,以在页面上的元素进入视图时触发。

We will grab the video element and observe it with observer API.

我们将获取视频元素,并使用观察者API对其进行观察。

const video = document.querySelector(".video-container video");


const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) {
      video.pause();
    } else {
      video.play();
    }
  });
}, {});


observer.observe(video);

Here’s what we did above:

这是我们上面所做的:

  • Selected video element from the page.

    从页面中选择的视频元素。
  • Created instance of intersection observer API and looped over the interested entries. Then we checked if the video is not intersecting with the viewport, we pause it otherwise we play it.

    创建相交观察器API的实例并遍历感兴趣的条目。 然后,我们检查视频是否与视口不相交,然后暂停它,否则我们将其播放。
  • Finally observed the video element.

    终于观察到了视频元素。

Here’s the sandbox: https://codesandbox.io/s/video-with-intersection-observer-gt6mk

这是沙箱: https : //codesandbox.io/s/video-with-intersection-observer-gt6mk

结果: (Result:)

Try scrolling the page past the video section, the video will pause and resume once scrolled back up. First step achieved. Let’s get to the second objective now.

尝试将页面滚动到视频部分之后,视频将暂停并在重新滚动后恢复播放。 第一步已实现。 现在让我们实现第二个目标。

页面可见性API (Page Visibility API)

Some basics first. This API is used to Detect Idle Browser Tabs. Using the Page Visibility API, we can detect when users aren’t viewing/interacting with our website to help them save precious computing resources!

首先了解一些基础知识。 此API用于检测空闲浏览器选项卡。 使用Page Visibility API ,我们可以检测到用户何时未查看/与我们的网站互动,从而帮助他们节省宝贵的计算资源!

The Page Visibility API was introduced in 2011, and includes several features that were added to the Document object:

Page Visibility API是在2011年引入的,其中包括一些添加到Document对象中的功能:

  • document.hidden: a read-only attribute that returns true when the tab/window is hidden

    document.hidden :只读属性,当隐藏标签页/窗口时返回true

  • document.visibilityState: a read-only attribute that returns a string value denoting the state of the tab/window: ‘hidden’ | ‘visible’ | ‘prerender’

    document.visibilityState :一个只读属性,该属性返回表示选项卡/窗口状态的字符串值: “可见” | 'prerender'

  • visibilitychange: an event that’s emitted whenever the tab/window’s visibility changes

    可见性更改:选项卡/窗口的可见性发生更改时发出的事件

For our scenario, we will listen for the visibilityChange event on the document and decide what action needs to be taken.

对于我们的场景,我们将监听文档上的visibleChange事件,并决定需要采取什么措施。

const video = document.querySelector(".video-container video");


const onVisibilityChange = () => {
  if (document.hidden) {
    video.pause();
  } else {
    video.play();
  }
};


document.addEventListener("visibilitychange", onVisibilityChange);

It simply does this — pauses the video when the document is hidden/switched tabs else play it.

它只是这样做-在隐藏/切换选项卡时暂停视频,否则播放视频。

Sandbox: https://codesandbox.io/s/video-with-page-visibility-api-yzbm6

沙箱: https//codesandbox.io/s/video-with-page-visibility-api-yzbm6

两个API一起 (Both API together)

Here’s the code altogether:

这是完全的代码:

const video = document.querySelector(".video-container video");
let playState = null;


const observer = new IntersectionObserver((entries) => {
  entries.forEach((entry) => {
    if (!entry.isIntersecting) {
      video.pause();
      playState = false;
    } else {
      video.play();
      playState = true;
    }
  });
}, {});


observer.observe(video);


const onVisibilityChange = () => {
  if (document.hidden || !playState) {
    video.pause();
  } else {
    video.play();
  }
};


document.addEventListener("visibilitychange", onVisibilityChange);

The only change is the addition of playState variable here which makes sure that the video state stays consistent. If we do not have this boolean check, you can see the issue happening in this sandbox by doing the following:

唯一的变化是在此处添加了playState变量,以确保视频状态保持一致。 如果我们没有此布尔检查,则可以通过执行以下操作查看此沙箱中发生的问题:

  • Scroll past the video. The video should be paused now due to intersection observer API

    滚动浏览视频。 由于路口观察器API,视频现在应该暂停
  • Switch to another tab. The video should stay paused due to page visibility check.

    切换到另一个标签。 由于页面可见性检查,视频应保持暂停状态。
  • Switch back to sandbox tab and you will notice that the video resumes. This is not the intended behavior as we only want to play it if its in the viewport. Hence we need the check.

    切换回沙盒标签,您会注意到视频继续播放。 这不是预期的行为,因为我们只想在视口中播放它。 因此,我们需要检查。

Here’s the final working sandbox: https://codesandbox.io/s/video-with-intersection-observer-gt6mk

这是最终的工作沙箱: https : //codesandbox.io/s/video-with-intersection-observer-gt6mk

I have also created a basic clone of Netflix. Here you can see the same features implemented: https://netflixx-8b384.firebaseapp.com/

我还创建了Netflix的基本克隆。 在这里您可以看到实现的相同功能: https : //netflixx-8b384.firebaseapp.com/

资源资源 (Resources)

普通英语JavaScript (JavaScript In Plain English)

Enjoyed this article? If so, get more similar content by subscribing to Decoded, our YouTube channel!

喜欢这篇文章吗? 如果是这样,请订阅我们的YouTube频道解码,以获得更多类似的内容

翻译自: https://medium.com/javascript-in-plain-english/video-pause-play-like-netflix-8570f903e0ff

netflix视频

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值