父子 z-index 问题(容器内)

问题描述 投票:0回答:1

我的孩子没有出现在我的父母之上,即使它的 z-index 比父母更高,我也遇到了问题。两个图像都出现在“检查”>“元素”中,因此我确信这不是这个问题。子条件也被传递到浏览器,因此这也是正确的。

这是相关的 CSS 片段:

.game-container {
  position: relative;
  width: 490px;
  height: 850px;
}

.player-sprite {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 64px;
  height: 64px;
  background-image: url('./sprites/Player.png');
  background-repeat: no-repeat;
  overflow: hidden;
}

.player-sprite.game-over {
  position: absolute;
  background-image: url('./sprites/Player_lose.png');
  z-index: 100;
}

.player-sprite.game-won {
  position: absolute;
  background-image: url('./sprites/Player_winning.gif');
  height: 80px;
  z-index: 100;
}

这是 Player.js,逻辑位于:

import React from 'react';

const Player = ({ playerX, playerY, direction, isMoving, gameOver, gameWon }) => {
    let statusClass = '';
    
    if (gameOver) {
        statusClass = 'game-over';
    } else if (gameWon) {
        statusClass = 'game-won';
    }

    const className = `player-sprite ${direction} ${isMoving ? 'moving' : 'stopped'} ${statusClass}`;

    return <div className={className} style={{ left: `${playerX}px`, bottom: `${playerY}px`}} />;
}

export default Player;

这就是当浏览器中满足 gameOver 条件并且检查每个未添加删除线的样式时会发生的情况(浏览器检测到背景图像,但不会出现)

every style not strikethrough-ed is checked

当我取消选中失踪的孩子时,父母就会出现。

enter image description here

顺便说一句,游戏容器 div 没有背景图像,因此父级或子级不会夹在它们之间或其他东西之间。身体是有背景的。此外,没有其他父子与玩家重叠。

任何见解将不胜感激,谢谢!

我尝试过为子级设置非常高的 z-index,而父级的 z-index 只有 1,我也尝试过让父级根本没有 z-index。我也尝试将

Opacity:0.99;
放在父类中,但同样的问题。

html css reactjs z-index
1个回答
0
投票

这似乎是由于

background-position
应用于
.player-sprite.up.stopped
规则中:

CSS rule

如果我们对于非工作实例及其背景图像考虑到这一点:

Sprite background image tooltip in Chrome devtools

background-position
会将此背景图像重新定位到元素外部,因为元素和背景图像只有 64 像素 × 64 像素:

┌─────────┐─────
│ bg      │  ↑
│ image   │  │
│         │192px
└─────────┘  │
             │
             ↓
┏━━━━━━━━━┓─────
┃ visible ┃
┃ element ┃
┃ bounds  ┃
┗━━━━━━━━━┛

要解决此问题,请考虑将

background-position
设置为
0 0
center
等,以使背景图像可见:

.player-sprite.up.stopped.gameover {
  background-position: center;
}
© www.soinside.com 2019 - 2024. All rights reserved.