【问题标题】:Change text color to white on any non-white background在任何非白色背景上将文本颜色更改为白色
【发布时间】:2019-08-20 19:56:50
【问题描述】:

使用mix-blend-mode: difference 在背景颜色为黑色时将文本颜色更改为白色效果很好。将鼠标移到文字上看效果:

const blackBox = document.querySelector(".black-box");
window.addEventListener('mousemove', function(event) {
  blackBox.style.left = `${event.pageX - 50}px`;
  blackBox.style.top = `${event.pageY - 50}px`;
});
.wrapper {
  background-color: white;
}
h1 {
  position: relative;
  z-index: 2;
  color: white;
  mix-blend-mode: difference;
}

.black-box {
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
  background-color: black;
}
<div class="wrapper">
  <h1>Lorem Ipsum</h1>
</div>
<div class="black-box"></div>

可以理解,如果背景不是黑色,则不会产生白色文本:

const box = document.querySelector(".box");
window.addEventListener('mousemove', function(event) {
  box.style.left = `${event.pageX - 50}px`;
  box.style.top = `${event.pageY - 50}px`;
});
.wrapper {
  background-color: white;
}
h1 {
  position: relative;
  z-index: 2;
  color: white;
  mix-blend-mode: difference;
}

.box {
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
  background-image: url("https://placekitten.com/100/100")
}
<div class="wrapper">
  <h1>Lorem Ipsum</h1>
</div>
<div class="box"></div>

有没有什么方法可以让文本在背景与白色不同时立即从黑色变为白色?

【问题讨论】:

  • 在这种特殊情况下还是通用解决方案?我怀疑混合混合模式在这里会有所帮助
  • 通用解决方案将是最佳的。好的,谢谢你的洞察力!我有一个可以改变的图像,用户可以用鼠标在文本上移动,并且文本应该像第一个代码 sn-p 一样从黑色变为白色。

标签: css mix-blend-mode


【解决方案1】:

这是一个依赖背景着色而不是mix-blend-mode 的想法。诀窍是使渐变具有与您移动的图像相同的尺寸以模拟混合模式:

const box = document.querySelector(".box");
const h1 = document.querySelector("h1");
window.addEventListener('mousemove', function(event) {
  box.style.left = `${event.pageX - 50}px`;
  box.style.top = `${event.pageY - 50}px`;
  
  h1.style.backgroundPosition = `${event.pageX - 50}px ${event.pageY - 50}px`;
});
.wrapper {
  background-color: white;
}
h1 {
  position: relative;
  z-index: 2;
  color: white;
  background: 
    /*gradient                   position   /    size  */
    linear-gradient(#fff,#fff) -100px -100px/100px 100px fixed no-repeat,
    #000;
  -webkit-background-clip: text;
  background-clip: text;
  -webkit-text-fill-color: transparent;
  color: transparent;
}

.box {
  width: 100px;
  height: 100px;
  position: absolute;
  z-index: 1;
  background-image: url("https://placekitten.com/100/100")
}
<div class="wrapper">
  <h1>Lorem Ipsum</h1>
</div>
<div class="box"></div>

我考虑过background-attachment:fixed 相对于视口放置渐变,因为您的元素是position:absolute,没有定位祖先,因此它也相对于视口定位。

【讨论】:

    猜你喜欢
    • 2014-01-19
    • 2019-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 2023-02-25
    • 2022-11-01
    相关资源
    最近更新 更多