簡體   English   中英

關鍵幀中的背景圖像在 Firefox 或 Internet Explorer 中不顯示

[英]Background-image in keyframe does not display in Firefox or Internet Explorer

我的網站上有幾個動畫,我剛剛意識到它們甚至沒有出現在 Firefox 或 Internet Explorer 中。 我在關鍵幀中有background-image 我這樣做是因為我在動畫中有不同百分比的不同圖像。

為什么background-image顯示在 Firefox 和 Internet Explorer 的關鍵幀內,有什么方法可以使這個工作?

根據規范background-image不是可動畫或可轉換的屬性。 但它似乎沒有說明當它用作過渡或動畫的一部分時應該如何處理或如何處理。 因此,每個瀏覽器似乎都以不同的方式處理它。 當 Chrome (Webkit) 顯示背景圖像時,Firefox 和 IE 似乎什么也不做。

在 oli.jp的一篇文章中找到的以下引用提供了一些有趣的信息:

雖然 CSS 背景和邊框模塊 Level 3 Editor's Draft 在撰寫本文時對 background-image 說“Animatable: no”,但在 Chrome 19 Canary 中出現了對 CSS 中交叉淡化圖像的支持。 在獲得廣泛支持之前,這可以通過圖像精靈和背景位置或不透明度來偽造。 要動畫漸變,它們必須是相同的類型。

從表面上看,Firefox 和 IE 似乎可以正確處理它,而 Chrome 則不然。 但是,事情並非如此簡單。 Firefox 在處理背景圖像上的過渡而不是動畫時似乎自相矛盾。 在轉換background-image ,它會立即顯示第二個圖像(將第一個div hover在代碼段中),而在設置動畫時,根本不會顯示第二個圖像(將第二個div hover在代碼段中)。

所以,結論是最好不要在 keyframes 內設置background-image 相反,我們必須像指定的@oli.jp 一樣使用background-positionopacity

 div { background-image: url(https://placehold.it/100x100); height: 100px; width: 100px; margin: 10px; border: 1px solid; } div:nth-of-type(1) { transition: background-image 1s ease; } div:nth-of-type(1):hover { background-image: url(https://placehold.it/100/123456/ffffff); } div:nth-of-type(2):hover { animation: show-img 1s ease forwards; } @keyframes show-img { to { background-image: url(https://placehold.it/100/123456/ffffff); } }
 <div></div> <div></div>


如果您有多個圖像應該在關鍵幀內以不同的百分比顯示,那么最好在開始時將所有這些圖像添加到元素上並為它們的位置設置動畫,如下面的代碼片段所示。 在 Firefox、Chrome 和 IE 中的工作方式相同

 div { background-image: url(https://placehold.it/100x100), url(https://placehold.it/100/123456/ffffff); background-size: 100% 100%; background-repeat: no-repeat; background-position: 0px 0px, 100px 0px; height: 100px; width: 100px; margin: 10px; border: 1px solid; } div:hover { animation: show-img 1s steps(1) forwards; } @keyframes show-img { to { background-position: -100px 0px, 0px 0px; } }
 <div></div>

或者,就像下面的代碼片段一樣。 基本上每個圖像與容器background-size相同,因為background-size設置為100% 100%但在任何給定時間只顯示一個圖像,因為它們與容器的大小相同。 0%50%顯示第一張圖像,因為它位於0px,0px (左上)而第二張圖像位於100px,0px (在右邊框之外)。 50.1% ,第一張圖片位於-100px,0px (左邊框外),第二張圖片位於0px,0px ,因此它是可見的。

 div { background-image: url(https://picsum.photos/id/0/367/267), url(https://picsum.photos/id/1/367/267); background-size: 100% 100%; /* each image will be 100px x 100px */ background-repeat: no-repeat; background-position: 0px 0px, 100px 0px; height: 100px; width: 100px; margin: 10px; border: 1px solid; animation: show-img 5s ease forwards; } @keyframes show-img { 0%, 50%{ background-position: 0px 0px, 100px 0px; /* initially 1st image will be shown as it it as 0px 0px */ } 50.1%, 100% { background-position: -100px 0px, 0px 0px; /* at 50.1% 2nd image will be shown as it it as 0px 0px */ } }
 <div></div>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM