拆分幻灯片兄弟姐妹,一个兄弟姐妹在悬停时会影响另一个兄弟姐妹

时间:2020-04-24 04:02:11

标签: javascript html css

我正在尝试实现与Navy.com标头类似的效果,在该标头上,您将鼠标悬停在一个同级上,然后滑动以占据大部分空间,同时缩小并隐藏另一个同级的内容。

由于无法选择以前的兄弟姐妹的CSS标准,我只能从一侧而不是另一侧获得效果。我了解仅靠CSS可能无法做到这一点。

预先感谢您的帮助!

这是我当前正在使用的代码:

.container {
  display: flex;
  flex-direction: row-reverse;
}

.b1 {
  display: flex;
  order: 2;
  width: 50%;
  height: 150px;
  padding: 10px;
  background-color: rgb(40, 251, 202);
  transition: all 0.5s;
}

.b2 {
  display: flex;
  width: 50%;
  order: 1;
  height: 150px;
  padding: 10px;
  background-color: rgb(227, 29, 103);
  transition: all 0.5s;
}

.b1:hover {
  width: 80%;
}

.b2:hover {
  width: 80%;
}

.b1:hover~.b2 {
  background-color: rgba(227, 29, 103, 0.4);
  width: 20%;
}

.b2:hover~.b1 {
  background-color: rgba(40, 251, 202, 0.4);
  width: 20%;
}

.b1:hover~.b2 span {
  display: none;
}

.b2:hover~.b1 span {
  display: none;
}
<div class="container">
  <div class="b2">
    <span>This content will show up directly in its container.</span>
  </div>
  <div class="b1">
    <span>This content will show up directly in its container.</span>
  </div>
</div>

1 个答案:

答案 0 :(得分:0)

进行一些重组,仅使用CSS就可以实现所需的效果。在此实现中,我使用:not CSS选择器和一些多级super.onLayout选择器(之所以起作用是因为:hover.container占用相同的空间)

尽管,这只是一个建议:利用flex的自动增长功能,并完全删除.child逻辑。这样,未悬停的组件的子组件将占据相等的空间,而悬停的组件的子组件仍将增长到80%的宽度。这样一来,您就可以动态添加更多项目,而不必更改硬编码的CSS。

width: 20%;
.container {
  display: flex;
}

.child {
  width: 50%;
  height: 150px;
  padding: 10px;
  transition: all 0.5s;
}

.child--red {
  background-color: rgba(227, 29, 103, 1);
}

.container:hover .child--red:not(:hover) {
  background-color: rgba(227, 29, 103, 0.4);
}

.child--green {
  background-color: rgba(40, 251, 202, 1);
}

.container:hover .child--green:not(:hover) {
  background-color: rgba(40, 251, 202, 0.4);
}

.container:hover .child:not(:hover) span {
  display: none;
}

.container:hover .child {
  width: 20%;
}

.container:hover .child:hover {
  width: 80%;
}