【问题标题】:Css inverting everything below an elementCss反转元素下方的所有内容
【发布时间】:2021-11-13 18:43:34
【问题描述】:

是否有可能使用 css 让一个元素反转它后面的所有内容,以便通过该元素下方的任何内容都将被反转?

在示例中,我希望圆圈在穿过黑色方块时为白色,否则为黑色。

.container {
  height: 500px;
  width: 500px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: white;
}

.invert {
  height: 300px;
  width: 300px;
  background-color: black;
}

.move {
  height: 50px;
  width: 50px;
  background-color: black;
  border-radius: 1000px;
  position: absolute;
  top: 0;
  left: 0;
  animation: move linear 5s infinite;
}

@keyframes move {
  0% {
transform: translate(0,0);
  }
  100% {
transform: translate(500px, 500px);
  }
}
<div class="container">
  <div class="invert">

  </div>
  <div class="move">

  </div>
</div>

这需要与结构无关,因为在我的实际实现中我使用大量随机移动的圆圈作为固定背景,我不知道它们何时会进入或退出正方形,以及圆形和正方形之间的关系页面之间会有所不同

我尝试过 filter: invert(1),但它并没有达到我需要的效果,我也很好奇它是否可以使用 svg 过滤器来完成。

非常感谢!

【问题讨论】:

    标签: javascript html css filter


    【解决方案1】:

    您可以在.invert 类中使用带有白色背景的mix-blend-mode: difference

    .container {
      height: 500px;
      width: 500px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: white;
    }
    
    .invert {
      height: 300px;
      width: 300px;
      background-color: #FFF;
      mix-blend-mode: difference;
      z-index: 1000;
    }
    
    .move {
      height: 50px;
      width: 50px;
      background-color: black;
      border-radius: 1000px;
      position: absolute;
      top: 0;
      left: 0;
      animation: move linear 5s infinite;
    }
    
    @keyframes move {
      0% {
    transform: translate(0,0);
      }
      100% {
    transform: translate(500px, 500px);
      }
    }
    <div class="container">
      <div class="invert">
    
      </div>
      <div class="move">
    
      </div>
    </div>

    这里的一个警告是它只能反转出现在它后面的元素。因此,如果您的 .move 对象需要在逆变器之后位于 DOM 中,您必须更改其中一个或另一个的 z-index 以使其正确呈现。

    【讨论】:

    • 非常感谢,我已经尝试过了,但可能在我的实施中做错了,明天再试一次,如果有效,请标记答案。
    • @elliott_l 需要注意的是mix-blend-mode,它只能与 DOM 中“背后”的元素交互。 filter 仅适用于内部元素,我不确定是否有任何东西会影响“前面”的元素。
    • 好的,谢谢我今天终于解决了,除了修复 z-index 事实证明我还必须将混合模式差异添加到 invert 元素的基本容器,而不是 invert 元素本身。我真的不知道为什么,但它现在工作得很好!
    猜你喜欢
    • 1970-01-01
    • 2013-11-16
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多