当背景颜色是黑色时,使用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>
如果背景与白色不同,有什么方法可以使文本从黑色变为白色呢?
发布于 2019-03-29 20:51:06
这里有一个依赖于背景颜色而不是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,没有定位祖先,所以它也相对于视口定位。
https://stackoverflow.com/questions/55424824
复制相似问题