我正在開發一個用 HTML、CSS 和 vanilla JavaScript 構建的“僵尸打地鼠”游戲。
我有僵尸從墳墓中上下彈出的影片,但是我無法弄清楚如何在他在泥土下時“隱藏”他,并在我為他上下彈出影片時逐漸顯露他.
運行下面的代碼片段來看看我的意思。(您可能需要向下滾動結果以查看正在發生的事情的全貌)
.background {
width: 220px;
z-index: 5;
}
.frontdirt {
width: 220px;
position: absolute;
left: 10px;
z-index: 15;
}
.zombie {
animation: popup 2s ease-in-out 10 forwards;
position: absolute;
width: 220px;
top:140px;
left:2px;
z-index: 10;
}
@keyframes popup {
0% {
transform: translateY(0px);
}
50% {
transform: translateY(-140px);
}
100% {
transform: translateY(0px);
}
}
<table>
<tr>
<td>
<img src="https://www.codeeverydamnday.com/images/beforezombie2.png" class="background" />
<img
src="https://www.codeeverydamnday.com/images/zombie.png"
class="zombie"
/>
<img
src="https://www.codeeverydamnday.com/images/groundfront2.png"
class="frontdirt" />
</td>
</tr>
<tr>
<td>
<img
src="https://www.codeeverydamnday.com/images/beforezombie2.png" class="background"
/>
</td>
</tr>
</table>
我首先嘗試使用 z-indexes 無濟于事,然后使用 CSS 定位,但我看不到任何其他方法可以在不使用絕對定位的情況下將其顯示在我需要的地方。
我目前正試圖弄清楚是否有辦法將影像保持在其起始位置,但用某種overflow: hidden
屬性隱藏掉在其容器(表格單元格)之外的部分。但是,由于它是絕對定位的,我已將其從檔案流中取出,因此它不會遵守任何容器邊界。
任何想法我可以如何以不同的方式定位它?有沒有辦法在不使用絕對值的情況下將僵尸定位在“背景”和“前塵”影像之間,以便它尊重容器邊界?或者我應該完全采用不同的方法嗎?
uj5u.com熱心網友回復:
我建議您使用 CSS Grid 規范。在這個例子中,我制作了一個外部網格來保存不同的“單元格”(我假設你想要一個經典的 Whackamole 設定),然后每個單元格另一個網格。使用 CSS Grid,您可以在不使用絕對定位的情況下將專案相互疊加。然后我只是給了影像相對位置并保留了你的 z-indexes。這樣溢位:隱藏適用于每個單元格。
這樣做有一個額外的好處,那就是使用fr
單位和網格的 minmax 函式有點回應,只需將影像設定為 100% 寬度,它們就會一起縮放。
旁注我將翻譯功能更改為基于百分比的功能,因此它可以在多種尺寸下作業,但如果您想更直接地控制布局,您也可以為每個網格單元設定固定寬度。
.grid {
display: grid;
grid-template-columns: repeat(4, minmax(220px, 1fr))
}
.cell {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 1fr;
overflow: hidden;
}
.background {
width: 100%;
z-index: 5;
grid-area: 1 / 2 / 1 / 2
}
.frontdirt {
width: 100%;
position: relative;
z-index: 15;
grid-area: 1 / 2 / 1 / 2
}
.zombie {
animation: popup 2s ease-in-out infinite forwards;
position: relative;
top: 50%;
width: 100%;
z-index: 10;
grid-area: 1 / 2 / 1 / 2
}
@keyframes popup {
0% {
transform: translateY(0);
}
50% {
transform: translateY(-50%);
}
100% {
transform: translateY(0);
}
}
<div class="grid">
<div class="cell">
<img src="https://www.codeeverydamnday.com/images/beforezombie2.png" class="background" />
<img src="https://www.codeeverydamnday.com/images/zombie.png" class="zombie" />
<img src="https://www.codeeverydamnday.com/images/groundfront2.png" class="frontdirt" />
</div>
<div class="cell">
<img src="https://www.codeeverydamnday.com/images/beforezombie2.png" class="background" />
</div>
</div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341080.html