视差视频进度滚动

发布于 2025-01-18 14:13:38 字数 162 浏览 4 评论 0原文

我想要创建一个视频视差背景,但我希望视频的进度与我在网页上的位置相对应。

例如:

  • 当我位于页面顶部时,视频时长为 0 秒,
  • 中间为总运行时间的 50%
  • ,只有当我到达页面底部时才结束。

I'm looking to create a video parallax background, but I want that the progress of the video corresponds to where I am on my webpage.

For example :

  • When im on the top of the page the video is at 0 seconds,
  • in the middle at 50% of its total runtime
  • and finishes only when I reach the bottom of the page.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

能否归途做我良人 2025-01-25 14:13:38

你必须将大问题分解为小问题。

首先,你需要获取视频的时长

var vid = document.getElementById("myVideo");
duration = vid.duration;

接下来,您需要获取以百分比表示的滚动量

function getVerticalScrollPercentage (elm) {
  var p = elm.parentNode
  return (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight ) * 100
}

接下来,您需要 动态设置视频的 currentTime (以秒为单位),您可以这样做:

vid.currentTime = duration * percentage / 100;

最后,您需要每当滚动量发生变化时,再次设置 currentTime。这是通过在 body 上使用事件侦听器来实现的。

object.addEventListener("scroll", myScript);

现在把它们放在一起:)

You have to break down the big problem into smaller problems.

First, you need to get your video's duration :

var vid = document.getElementById("myVideo");
duration = vid.duration;

Next, you need to get the scroll amount in percentage

function getVerticalScrollPercentage (elm) {
  var p = elm.parentNode
  return (elm.scrollTop || p.scrollTop) / (p.scrollHeight - p.clientHeight ) * 100
}

Next, you need to dynamically set your video's currentTime (in seconds), you can do it this way :

vid.currentTime = duration * percentage / 100;

And finally, you need to set the currentTime again, whenever the scroll amount changes. That is achieved by using an event listener, on the body for example.

object.addEventListener("scroll", myScript);

Now put it all together :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文