简体   繁体   English

CSS-根据背景更改文本颜色

[英]CSS - Change text color depending on background

I have a simple layout consisting of three full height divs and a fixed header bar. 我有一个简单的布局,包括三个全高div和一个固定的标题栏。

 body,html { padding:0; margin:0; } .header { position:fixed; width:100%; height:50px; color:white; margin:20px; } .section1 { background:black; height:100vh; display: flex; align-items: center; justify-content: center; color:white; } .section2 { background:white; height:100vh; display: flex; align-items: center; justify-content: center; } .section3 { background:black; height:100vh; display: flex; align-items: center; justify-content: center; color:white; } 
 <div class="header"> Header Content </div> <div class="wrapper"> <div class="section1"> Section One Content </div> <div class="section2"> Section Two Content </div> <div class="section3"> Section Three Content </div> </div> 

I am trying to make the header bar text colour change to black when it rolls over the section with the white background. 我试图将标题栏文本颜色滚动到带有白色背景的部分时变为黑色。

I have seen a couple of jQuery plugins which should work to achieve this but I am trying to avoid any unnecessary scripts. 我已经看到了几个可以实现此目标的jQuery插件,但我试图避免任何不必要的脚本。

Would the CSS mix-blend-mode function allow me to achieve this? CSS mix-blend-mode函数是否可以实现这一目标? Does anybody have an example they can point me to of something similar being achieved? 有没有人能举例说明他们可以实现类似的目标?

You can use mix-blend-mode:difference 您可以使用mix-blend-mode:difference

 body, html { padding: 0; margin: 0; } .header { position: fixed; width: 100%; height: 50px; margin: 20px; color:#fff; mix-blend-mode: difference; } .section1, .section2, .section3{ background: black; height: 100vh; display: flex; align-items: center; justify-content: center; color: white; } .section2 { background: white; color:#000; } 
 <div class="header"> Header Content </div> <div class="wrapper"> <div class="section1"> Section One Content </div> <div class="section2"> Section Two Content </div> <div class="section3"> Section Three Content </div> </div> 

You can do it with jquery, when something happens, do: 您可以使用jquery进行操作,如果发生某些情况,请执行以下操作:

$('yourdiv1').css({"color": "black"})
$('yourdiv2').css({"background-color": "white"})

To set it to default just: 要将其设置为默认值:

$('yourdiv1').css({"color": ""})
$('yourdiv2').css({"background-color": ""})

Also add transitions to make it look really nice. 还添加过渡以使其看起来非常漂亮。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM