javascript - 通过 javascript 将 CSS 样式添加到特定类

标签 javascript jquery css

我得到了这些代码行并且只想将它们添加到特定的 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/

相关文章:

php - Chrome 和 Firefox 处理 JavaScript/HTML 的方式不同

javascript - 带有百分比的 Ajax 加载进度条

javascript - 使用客户端图形和动态 classbreakrenderer 的打印任务不起作用

JQuery UI - 多态地使用小部件

javascript - canvas-裁剪不同形状的图像

html - 我需要向 CSS 类添加哪些规则/声明才能启用无单个单词截断的自动换行?

css - 在 css 中使用 float 时 jqGrid 标题变大

javascript - 如果有办法做 background-size : cover and still be able to scroll around the image

php - jQuery FileTree 无法读取本地共享文件夹?

javascript - angularjs $compile 产生 ng-repeat 重复行