使用CSS实现类似TikToken的滚动

des4xlb0  于 2023-02-06  发布在  其他
关注(0)|答案(1)|浏览(173)

我的网页上有视频显示在一个可滚动的列表中,每个视频都覆盖了整个屏幕,如下所示:

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Videos</title>
  <style>
    body {
      background-color: #090909;
    }

    .video-box {
      display: flex;
      align-items: center;
    }

    .video-box video {
      box-sizing: border-box;
      padding: 8px;
      margin: 0 auto;
      max-height: 100vh;
      max-width: 100%;
    }
  </style>
</head>

<body>
  <section class="videos">
    <div class="video-box">
      <video preload="none" poster="vert1.png" autoplay muted loop playsinline>
        <source src="vert1.mp4" type="video/mp4">
      </video>
    </div>
    <div class="video-box">
      <video preload="none" poster="vert2.png" autoplay muted loop playsinline>
        <source src="vert2.mp4" type="video/mp4">
      </video>
    </div>
    <div class="video-box">
      <video preload="none" poster="vert1.png" autoplay muted loop playsinline>
        <source src="vert1.mp4" type="video/mp4">
      </video>
    </div>
    <div class="video-box">
      <video preload="none" poster="vert2.png" autoplay muted loop playsinline>
        <source src="vert2.mp4" type="video/mp4">
      </video>
    </div>
  </section>
</body>

</html>

我的实现中缺少的部分是让视频像TikTok或YouTube Shorts那样快速播放。我尝试用fullPage.js的JavaScript实现它,但发现将脚本放入网页代码的额外工作存在问题。仅用HTML和CSS就能实现吗?

xlpyo6sf

xlpyo6sf1#

为此,创建了page-snap-*CSS properties
要在示例中使页面对齐,只需添加两个额外的CSS属性:

<style>
    html /* IMPORTANT: scroll-snap-type won't work with body selector, so replace it with html */ {
      background-color: #090909;
      scroll-snap-type: y mandatory; /* Define snapping behavior. "y" indicates vertical behavior, "mandatory" won't allow the user to stay in-between two pages. */
    }

    .video-box {
      display: flex;
      align-items: center;
      scroll-snap-align: start; /* Define snapping target. Can also be "center" or "end". */
    }

    .video-box video {
      box-sizing: border-box;
      padding: 8px;
      margin: 0 auto;
      max-height: 100vh;
      max-width: 100%;
    }
  </style>

相关问题