css - 在任何非白色背景上将文本颜色更改为白色
问题描述
当背景颜色为黑色时,将文本颜色更改为白色效果很好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>
有什么方法可以使文本在背景与白色不同时立即从黑色变为白色?
解决方案
这是一个依赖背景着色而不是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
没有定位祖先,因此它也相对于视口定位。
推荐阅读
- java - 在 Android WebView 上访问位置
- python - 日期所需的 strptime 日期格式,例如 `12/06/16 19:33`
- zurb-foundation - Foundation Zurb 当 Reveal 开场动画完成后,做某事
- reactjs - 意外的令牌,预期的“)”在 axios try-catch 语句中
- html - html中的导航问题
- mongodb - 在mongodb的字符串数组中查找和替换
- django - 如何在 django 中循环查询?
- javascript - 在生产构建中是否可以(全局)访问反应状态变量?
- mfc - C++(MFC) - 对话框阴影残像
- python - Creating a pdf file with a python script