简体   繁体   中英

How do I use CSS to alter the colour of my logo when I scroll onto a different background colour

I currently have a white SVG logo that I am using as my website is mostly dark backgrounds. However, I do have a section that is white so I am looking to change the colour of the logo to black while scrolling through the white section.

Here is a copy of the logo code and white section:

<!-- Logo -->
<div class="logo" style="display: block;">
  <a href="#home"></a> 
</div>

<!-- About -->
<div class="scrollview about">
  <div class="col-sm-3">

  </div>
</div>

Here is my current styles:

.logo {
   position: fixed;
   top: 0;
   left: 0;
   margin: 20px;
   padding: 2.8em 2.8em;
   z-index: 9;
}
.logo a {
   width: 95px;
   height: 16px;
   display: block !important;
   background-image: url('../img/logo-light.png') transparent 0 0 no-repeat;
   background-image: none,url('../img/logo-light.svg');
}
.about {
  padding: 12.25em 10.25em;
  margin: 0;
  overflow: hidden;
  background: #fff;
  width: 100%;
  height: auto;
  z-index: 3;
}

I'm not sure if it can be done using only CSS, but if someone can even point me towards a plugin or script it would be much appreciated.

Thanks

You can't use CSS like that to change the style of an SVG that's in a separate file. CSS rules do not cross document boundaries.

To style the SVG, you would need to need to inline it in your HTML page.

Assuming you made that change, then you could add a scroll event handler to the page and watch the position of the logo. If you detect it is at the right point on the page (ie. it is over the white section), then you could add a class to it (or the <a> or the <div> ). The class would change the colour of the logo using fill: black , or whatever.

Have you considered an easier solution? Such as giving the logo a dark outline, so that it stands out when over the white background?

The fill property in CSS is for filling in the color of a SVGs .

svg {
    fill: currentColor;
 }

But you can't change the color of your logo for specific section of your site.

i check your demo link and I found out that they are use jquery to add and remove css class from there logo. So you need add jquery 2.3.+ get the value of the bottom of the #main element by adding the offset of that element plus its height, set it as a variable

var mainbottom = $('#main').offset().top + $('#main').height();

Now on scroll add function

$(window).on('scroll',function()

and in it just add

stop = Math.round($(window).scrollTop());
    if (stop > mainbottom) {
        $('.logo').addClass('logo-dark');
    } else {
        $('.logo').removeClass('logo-dark');
   } 

Here's demo on codepen I made for you hope this will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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