为 html 编辑器应用条件 css 样式 sheet

Apply conditional css style sheet for html editor

例如,

(如果)我有这个 HTML 形式的二维编辑器:

我有一个名为“filter”的 css 文件,代码为:

monochrome {
    filter: grayscale(var(--value, 100%)); --value:100%;
}

小编的Dragon在canvas上放置“单色”滤镜的方法是什么?

<link rel="stylesheet" type="text/css" href="monochrome.css">
if (data[Blocks].id === "dragon") {
         
        *What should I write here in order to apply the css filter (only to the dragon sprite, when placing?*

}

第一步是将 CSS 单色 定义转换为 class。这只需在名称前加上一个点即可完成,例如

.monochrome {
    filter: grayscale(var(--value, 100%));
}

以这种方式定义它可以让多个 HTML 元素重复使用 - 因为您的 Dragon 可能不是您要应用过滤器的唯一元素。

因为我们有一个 CSS class 现在我们可以通过调用

theObject.classList.add("monochrome");

theObject.classList.remove("monochrome");

while add / remove 顾名思义是添加或删除引号中给出的 CSS class。

但是我们如何获得对 theObject 的引用? 如果你已经使用它的 id 属性 给你的 HTML 元素一个唯一的 id,这很容易:

document.getElementById("id")

不过要小心 - 它与您在 post.

中提到的 id 不同

这是一个例子:

document.getElementById("monochromeButton").addEventListener("click", function() {
  document.getElementById("dragon").classList.add("monochrome");
});
document.getElementById("removeButton").addEventListener("click", function() {
  document.getElementById("dragon").classList.remove("monochrome");
});
.monochrome {
  filter: grayscale(var(--value, 100%));
}
<button id="monochromeButton">
monochrome
</button>
<button id="removeButton">
remove filter
</button>
<br>
<img id="dragon" src="https://picsum.photos/id/237/200/140">