首页 > 解决方案 > 文本高亮作为 CSS 掩码?

问题描述

我想知道是否可以重现此文本效果:

在此处输入图像描述

它应该看起来好像文本突出显示降低了图像的不透明度。我想你需要的是背景层的副本,在文本高亮的形状/位置中被掩盖。但是有没有办法真正让这些蒙版根据文本行自动调整大小/重新定位?或者有什么其他方法可以达到效果?

这可能更好地解释我所追求的: 在此处输入图像描述

标签: csstextmaskmasking

解决方案


您可能正在寻找 CSS 属性background-attachment: fixed。这确实有一个警告,即背景将不再随页面滚动并保持静态,但这样可以保证元素背景和容器背景之间的重叠保持不变。通过 javascript 修复了滚动问题,只需少量开销成本,具体取决于浏览器渲染/重新定位的图形的重量。

然后,您只需将相同的背景应用于包含元素的背景(在我的情况下为 .wrap)和包含元素的文本(在我的情况下为换行),您将获得所需的效果,如第二张图片所示。

然后将标记放在段落元素中并重复文本两次。一次在段落中,一次在标记内。
然后将段落设置为相对位置,并将标记设置为绝对位置,这样它们就可以完美地重叠。这是为了抵消包装是透明的并且不能正确显示文本,因为文本也变得透明。

.wrap, .wrap mark {
   background-image: url('https://i.imgur.com/hAodNjT.jpg');
   background-attachment: fixed;
}
.wrap p {
  position: relative;
}
.wrap mark {
   position: absolute;
   top: 0px;
   left: 0px;
   opacity: 0.4;
}
img {
   width: 300px;
   height: auto;
}
.wrap {
   padding-top:160px;
   position: relative;
   width: 400px;
   height: 400px;
}
.wrap img {
   position:absolute;
   top:60px;
   
   z-index:0;
}
.wrap p {
    position:relative;
    z-index: 1;
}
<div class="wrap">
  <img src="https://i.imgur.com/cULI8TG.png">
  <p>some text that runs over the image<mark>some text that runs over the image</mark></p>
  <p>some other text that runs over the image<mark>some other text that runs over the image</mark></p>
</div>

带有背景滚动修复,滚动时确实会引入更多开销

var $affected = $('.wrap, .wrap mark');
let handler = (e) => {
    $affected.css({'background-position' : '-'+window.scrollX+'px -'+window.scrollY+'px'});
}
$(window).on('resize scroll', handler);
.wrap, .wrap mark {
   background-image: url('https://i.imgur.com/hAodNjT.jpg');
   background-attachment: fixed;
}
.wrap p {
  position: relative;
}
.wrap mark {
   position: absolute;
   top: 0px;
   left: 0px;
   opacity: 0.4;
}
img {
   width: 300px;
   height: auto;
}
.wrap {
   padding-top:160px;
   position: relative;
   width: 400px;
   height: 400px;
}
.wrap img {
   position:absolute;
   top:60px;
   
   z-index:0;
}
.wrap p {
    position:relative;
    z-index: 1;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrap">
  <img src="https://i.imgur.com/cULI8TG.png">
  <p>some text that runs over the image<mark>some text that runs over the image</mark></p>
  <p>some other text that runs over the image<mark>some other text that runs over the image</mark></p>
</div>


推荐阅读