1. 開発者向けのウェブ技術
  2. Web API
  3. Animation
  4. commitStyles()

このページはコミュニティーの尽力で英語から翻訳されました。MDN Web Docs コミュニティーについてもっと知り、仲間になるにはこちらから。

View in English Always switch to English

Animation: commitStyles() メソッド

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since ⁨2020年7月⁩.

commitStyles()ウェブアニメーション APIAnimation インターフェイスのメソッドで、アニメーションの現在のスタイルの計算値をターゲット要素の style に書き込みます。 commitStyles() はアニメーションが自動削除されていてもうまく動作します。

commitStyles()fill と組み合わせて使用することができ、アニメーションが終わった後も最終的な状態を維持させることができます。同じ効果は fill だけでも得られますが、無期限に満たすアニメーションを使用することは推奨されません。アニメーションはすべての静的スタイルよりも優先されますので、無期限の塗りつぶしアニメーションは対象とする要素が通常のスタイル設定をされることを妨げる可能性があります。

commitStyles() を使用することができます スタイル設定は要素の style 属性に書き込まれます。

構文

js
commitStyles()

引数

なし。

返値

なし (undefined)。

アニメーションの最後の状態を確定

この例では、"Commit styles" と "Fill forwards" とラベル付けされた2つのボタンがあります。どちらのボタンもクリックするとアニメーションし、アニメーションの最終状態を維持します。

しかし、異なる点は、 "Fill forwards" は fill: "forwards" これは、ブラウザーがアニメーションの状態を無期限に、あるいは自動的に除去されるまで維持しなければならないことを意味しています。

しかし、 "Commit styles" ボタンはアニメーションが終了するのを待ち、 commitStyles() を呼び出されてからアニメーションを取り消しますので、完了したスタイルはアニメーションの状態ではなく style 属性の値として取り込まれます。

HTML

html
<button class="commit-styles">Commit styles</button>
<br />
<button class="fill-forwards">Fill forwards</button>
button {
 margin: 0.5rem;
}

JavaScript

js
const commitStyles = document.querySelector(".commit-styles");
let offset1 = 0;
commitStyles.addEventListener("click", async (event) => {
 // Start the animation
 offset1 = 100 - offset1;
 const animation = commitStyles.animate(
 { transform: `translate(${offset1}px)` },
 { duration: 500, fill: "forwards" },
 );
 // Wait for the animation to finish
 await animation.finished;
 // Commit animation state to style attribute
 animation.commitStyles();
 // Cancel the animation
 animation.cancel();
});
const fillForwards = document.querySelector(".fill-forwards");
let offset2 = 0;
fillForwards.addEventListener("click", async (event) => {
 // Start the animation
 offset2 = 100 - offset2;
 const animation = fillForwards.animate(
 { transform: `translate(${offset2}px)` },
 { duration: 500, fill: "forwards" },
 );
});

結果

仕様書

Specification
Web Animations
# dom-animation-commitstyles

ブラウザーの互換性

関連情報

Help improve MDN

Learn how to contribute

This page was last modified on by MDN contributors.

AltStyle によって変換されたページ (->オリジナル) /