gpt4 book ai didi

javascript - 根据背景颜色更改元素颜色黑色或白色

转载 作者:搜寻专家 更新时间:2023-10-31 08:22:36 25 4
gpt4 key购买 nike

我正在建立一个新网站,我想根据背景颜色或图像更改 Logo 颜色(即 position: fixed)。

我在 this site 上找到了一个例子.您可以查看 Logo 和一些元素如何根据背景改变颜色。

body {
margin: 0;
}

.logo img {
position: fixed;
width: 100px;
}

.black {
background: black;
width: 100%;
height: 400px;
}

.yellow {
background: yellow;
width: 100%;
height: 400px;
}

.red {
background: red;
width: 100%;
height: 400px;
}

.imageBg {
background: url(https://images.pexels.com/photos/2208895/pexels-photo-2208895.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260);
width: 100%;
height: 400px;
background-size: cover;
}
<div class="logo">
<img src="http://www.clker.com/cliparts/n/y/a/M/G/h/fdl-logo.svg">
</div>

<!-- change logo color to: black -->
<section class="yellow"></section>

<!-- change logo color to: white -->
<section class="black"></section>

<!-- change logo color to: white -->
<section class="red"></section>

<!-- change logo color to: black -->
<section class="yellow"></section>

<!-- change logo color to: white -->
<section class="imageBg"></section>

这是我的 fiddle :https://jsfiddle.net/o0gnayht/

最佳答案

通过使用 filter:invert(),您可以将 Logo 颜色从黑色更改为白色。如果您在 onscroll 事件中使用 jquery,您可以根据最接近顶部的 section

调用 filter

$(window).scroll(function ()
{
var windowTop = Math.max($('body').scrollTop(), $('html').scrollTop());
$('section').each(function (index)
{
if (windowTop > ($(this).position().top - 100))
{
if ($(this).hasClass('yellow'))
{
$('.logo img').css('filter', 'invert(0)');
}
else
{
$('.logo img').css('filter', 'invert(1)');
}
}
});
}).scroll();
body {
margin: 0;
}

.logo img {
position: fixed;
width: 100px;
}

.black {
background: black;
width: 100%;
height: 400px;
}

.yellow {
background: yellow;
width: 100%;
height: 400px;
}

.red {
background: red;
width: 100%;
height: 400px;
}

.imageBg {
background: url(https://images.pexels.com/photos/2208895/pexels-photo-2208895.jpeg?auto=compress&cs=tinysrgb&dpr=2&h=750&w=1260);
width: 100%;
height: 400px;
background-size: cover;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="logo">
<img src="http://www.clker.com/cliparts/n/y/a/M/G/h/fdl-logo.svg">
</div>

<!-- change logo color to: black -->
<section class="yellow"></section>

<!-- change logo color to: white -->
<section class="black"></section>

<!-- change logo color to: white -->
<section class="red"></section>

<!-- change logo color to: black -->
<section class="yellow"></section>

<!-- change logo color to: white -->
<section class="imageBg"></section>

关于javascript - 根据背景颜色更改元素颜色黑色或白色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55981122/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com