ScrollTimeline
Limited availability
This feature is not Baseline because it does not work in some of the most widely-used browsers.
Giao diện ScrollTimeline của Web Animations API đại diện cho một scroll progress timeline (xem CSS scroll-driven animations để biết thêm chi tiết).
Truyền một thực thể ScrollTimeline vào hàm khởi tạo Animation() hoặc phương thức animate() để chỉ định nó làm timeline kiểm soát tiến trình của animation.
Hàm khởi tạo
ScrollTimeline()-
Tạo một thực thể đối tượng
ScrollTimelinemới.
Thuộc tính phiên bản
Giao diện này cũng kế thừa các thuộc tính từ lớp cha, AnimationTimeline.
Phương thức phiên bản
Giao diện này kế thừa các phương thức từ lớp cha, AnimationTimeline.
Ví dụ
>Hiển thị nguồn và trục của scroll progress timeline
Trong ví dụ này, chúng ta tạo animation cho một phần tử có class là box dọc theo view progress timeline, nó di chuyển ngang màn hình khi tài liệu cuộn. Chúng ta hiển thị phần tử source và axis cuộn vào một phần tử output ở góc trên bên phải.
HTML
HTML cho ví dụ được hiển thị bên dưới.
<div class="content"></div>
<div class="box"></div>
<div class="output"></div>
CSS
CSS cho ví dụ trông như sau:
.content {
height: 2000px;
}
.box {
width: 100px;
height: 100px;
border-radius: 10px;
background-color: rebeccapurple;
position: fixed;
top: 20px;
left: 0%;
}
.output {
font-family: "Helvetica", "Arial", sans-serif;
position: fixed;
top: 5px;
right: 5px;
}
JavaScript
Trong JavaScript, chúng ta lấy tham chiếu đến các <div> box và output, sau đó tạo một ScrollTimeline mới, chỉ định phần tử sẽ điều khiển tiến trình scroll timeline là phần tử document (<html>), và trục cuộn là trục block. Sau đó chúng ta tạo animation cho phần tử box bằng Web Animations API. Cuối cùng, chúng ta hiển thị phần tử nguồn và trục trong phần tử output.
const box = document.querySelector(".box");
const output = document.querySelector(".output");
const timeline = new ScrollTimeline({
source: document.documentElement,
axis: "block",
});
box.animate(
{
rotate: ["0deg", "720deg"],
left: ["0%", "100%"],
},
{
timeline,
},
);
output.textContent = `Timeline source element: ${timeline.source.nodeName}. Timeline scroll axis: ${timeline.axis}`;
Kết quả
Cuộn để xem hộp được tạo animation.
Thông số kỹ thuật
| Specification |
|---|
| Scroll-driven Animations> # scrolltimeline-interface> |