我得到了这些代码行并且只想将它们添加到特定的 div 类。因此,如果背景较暗,则应为 filter: invert(1);
,当背景较亮时,应为 filter: invert(0);
。我怎样才能做到这一点?希望你能帮助我...我对 js 的理解还处于初级阶段。
function isDark( color ) {
var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
return ( match[1] & 255 )
+ ( match[2] & 255 )
+ ( match[3] & 255 )
< 3 * 256 / 2;
}
$('div').each(function() {console.log($(this).css("background-color"))
$(this).css("filter", isDark($(this).css("background-color")) ? 'invert(1)' : 'invert(0)');
});
最佳答案
您可以在 if
else
语句中单独检查条件,如下所示。
$('div').each(function() {
var color = $(this).css("background-color");
if (isDark(color)) {
$(this).css("filter", 'invert(1)');
} else {
$(this).css("filter", 'invert(0)');
}
});
或
如果你想添加一个css class
,你可以这样做
$('div').each(function() {
var color = $(this).css("background-color");
if (isDark(color)) {
$(this).addClass("inverted");
} else {
$(this).addClass("not-inverted");
}
});
其中可以为您的 CSS 中的新 class
添加样式,如下所示。
.inverted {
filter: invert(1);
}
.not-inverted {
filter: invert(0);
}
请参阅下面的代码段。
function isDark(color) {
var match = /rgb\((\d+).*?(\d+).*?(\d+)\)/.exec(color);
return (match[1] & 255) +
(match[2] & 255) +
(match[3] & 255) <
3 * 256 / 2;
}
/*
$('div').each(function() {console.log($(this).css("background-color"))
$(this).css("filter", isDark($(this).css("background-color")) ? 'invert(1)' : 'invert(0)');
}); */
$('div').each(function() {
var color = $(this).css("background-color");
if (isDark(color)) {
$(".logo").css("filter", 'invert(1)');
} else {
$(".logo").css("filter", 'invert(0)');
}
});
body {
height: 400vh;
}
.logo {
position: fixed;
top: 40px;
right: 20px;
background-image: url(https://image.freepik.com/free-vector/bicycle-shop-logo-design-vector_53876-40626.jpg);
background-repeat: no-repeat;
background-size: 100px;
height: 100px;
width: 100px;
background-color: black;
}
.blabla {
background-color: black;
height: 50vh;
}
.blablabla {
background-color: grey;
height: 50vh;
}
.blablablabla {
background-color: red;
height: 50vh;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="logo"></div>
<div class="blabla">test</div>
<div class="blablabla">test</div>
<div class="blablablabla">test</div>
关于javascript - 通过 javascript 将 CSS 样式添加到特定类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58529923/