React 中绝对定位元素的下拉菜单重叠问题

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

我已经实现了一个输入元素,它显示一个下拉菜单,其中包含焦点时的搜索建议(onFocus)。下拉菜单出现在输入下方,当我退出输入字段时消失,效果很好。不过,我还有一个名为

People
的组件,其中包含使用
position: absolute
定位的个人图像。这些图像彼此略有重叠。问题是,当下拉菜单出现时,它位于
People
组件后面,而我希望它覆盖
People
组件

人员组件的代码:

const People = () => {
  const peopleImages = [
    // URLs of people images
  ];

  return (
    <>
      {peopleImages.map((image, index) => (
        <img
          key={index}
          src={image}
          alt={`Person ${index + 1}`}
          className="home__header-people_roundImage"
          style={{
            left: index * -12 + 'px',
          }}
        />
      ))}
      <p>2,500 people booked Tommorowland Event in the last 24 hours</p>
    </>
  );
};

人物组件样式:

.home__header-people {
  margin-top: 28px;
  display: flex;
  flex-wrap: wrap;
  &_roundImage {
    position: relative;
    width: 36px;
    width: 36px;
    border-radius: 50%;
    border: 2px solid #fff;
  }
  p {
    margin-top: 10px;
    margin-left: -60px;
    color: #fff;
    font-family: Poppins;
    font-size: 12.537px;
    font-weight: 500;
  }
}
const DropDownInput = () => {
  return (
    <div className="home__header-form_dropDownInput">
      <p>Finland, Helsinki</p>
      <p>Italy, Madrid</p>
      <p>Greece, Athens</p>
    </div>
  );
};

下拉组件样式:

.home__header-form_dropDownInput {
  z-index: 2;
  width: 200px;
  height: 200px;
  position: absolute;
  padding: 5px;

  border-radius: 5px;
  background-color: #c9cbc2;
  top: 100px;
}

表单组件代码:

const Form = () => {
  const [isTyping, setIsTyping] = useState(false);

  return (
    <>
      <input
        type="text"
        placeholder="Where to?"
        onFocus={() => setIsTyping(true)}
        onBlur={() => setIsTyping(false)}
      />
      {isTyping && <DropDownInput />}

      {/* Rest of the form */}
    </>
  );
};

HomeHeader 组件的代码:

const HomeHeader = () => {
  return (
    <header className="home__header">
      <div className="home__header-title">
        {/* Title content */}
      </div>
      <form className="home__header-form">
        <Form />
      </form>
      <div className="home__header-people">
        <People />
      </div>
    </header>
  );
};

问题: 如何使下拉菜单覆盖

People
组件而不是位于其后面?我尝试过调整
z-index
值,但没有达到预期的效果。还有什么我应该考虑的吗?

Issue image

我还为您提供了组件结构方案:

HomeHeader
├── People
│   ├── Person 1
│   ├── Person 2
│   ├── ...
│   └── Person 7
└── Form
    ├── Input (with Dropdown)
    ├── Divider
    ├── Travel Type
    ├── Divider
    ├── Duration
    └── Submit Button

我尝试使用

z-index
属性来解决此问题。我将下拉菜单的
z-index
设置为 2,将
People
组件设置为 0。

html css reactjs web styling
1个回答
0
投票

如果具有较高 z-index 的元素是具有较低 z-index 的元素的子元素,则堆叠上下文将限制在父元素内。这意味着子级较高的 z-index 不一定会使其与父级之外的其他元素重叠。

你可以使用

position: fixed;

在组件或元素之一上,因此它将始终位于顶部或更改堆叠顺序。无论你需要什么,都必须是父母。

© www.soinside.com 2019 - 2024. All rights reserved.