首页 > 解决方案 > 如何在 React 中管理 4 层的 Z-index?

问题描述

如何设置 z-index,以便 4 层如下:

  1. 背景颜色
  2. logoImg(不透明度为 00.7 的 png)(!)
  3. 圆图 (png)
  4. 倒计时时钟(文本)

我尝试以各种可能的方式更改 z-index,但我无法得到 3. circleImg 和 4. coundownClock 重叠。

#1。背景颜色和#2。logoImg 正确设置为背景

TimerScreen.js:

 import React from 'react';
import UIfx from 'uifx';
import Logo from "../images/logo.png";
import Circle from "../images/circle.png";
import {
  BrowserRouter as Router,
  Switch,
  Route,
  Link
} from "react-router-dom";


class TimerScreen extends React.Component {

state = {
  minutes: 3,
  seconds: 0,
  reps: 3
}

  render() {

  const { minutes, seconds, reps } = this.state

      return (


    <div className="mainDiv" >

               <img
            className="logoImg"
            style={{
              width: "100%",
              opacity: "0.07",
                    position: "absolute",
                  zIndex: "-1"
                          }}
            src={Logo}
            alt="berolina-stralau logo"
        />             


          <div className="coundownClock">  { minutes < 10 ? `0${ minutes }` : minutes }:{ seconds < 10 ? `0${ seconds }` : seconds } </div>

          <img id="circleImg" src={Circle} />
          <div className="repetitionsCount"> <i>reps left: {reps}</i> </div>


            <div id="buttonDiv">
                                <Link to="/TimerScreen"
        className="goButton">PAUSE</Link>

        </div>
            <br />

        </div>

      );
    }

}
export default TimerScreen;

App.css 部分:

circleImg {
    width: 100%;
    margin-bottom: 40px;
    position: "absolute";
    z-index: "0";
}

.coundownClock {
    display: flex;
    justify-content: center;
    font-size: 111px;
    font-weight: bold;
    position: "relative";
    z-index: "1";
}

github.com FilipZafran/Interval-Timer 上的完整代码

标签: reactjsz-index

解决方案


来自https://www.w3schools.com/cssref/pr_pos_z-index.asp的定义:

z-index 属性指定元素的堆栈顺序。

具有较大堆栈顺序的元素始终位于具有较低堆栈顺序的元素之前。

注意:z-index 仅适用于定位元素(位置:绝对、位置:相对、位置:固定或位置:粘性)。

所以确保你的元素有一个位置和 z-index 来创建想要的顺序。如果我理解正确,那将是:

  1. 背景颜色 -> z-index: 0
  2. logoImg(不透明度为 00.7 的 png)(!)-> z-index:1
  3. circleImg (png) -> z-index: 2
  4. 倒计时时钟(文本)-> z-index: 3

然后背景颜色在后面,而 countdownClock 在前面

作为建议:将要堆叠的元素包装在一个其中有position: relative。在里面放置所有要堆叠的元素position: absolute和用于创建订单的 z-index


推荐阅读