0

例如,

(如果)我有这个 HTML 格式的 2d 编辑器: 在此处输入图像描述

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

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

Dragon将“单色”滤镜(龙精灵)放置到画布上时,将“单色”滤镜应用于编辑器的方法是什么?

<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?*

}
4

1 回答 1

0

第一步是将 CSS单色定义变成一个类。这只是通过在名称前面加上一个点来完成,例如

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

以这种方式定义它使得它可以被多个 HTML 元素重用——因为你的 Dragon 可能不是你想要应用过滤器的唯一元素。

由于我们现在有一个 CSS 类,我们可以通过调用

theObject.classList.add("monochrome");

或者

theObject.classList.remove("monochrome");

而 add / remove 顾名思义,添加或删除引号中给出的 CSS 类。

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

document.getElementById("id")

不过要小心 - 它与您在帖子中提到的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">

于 2021-01-27T19:43:43.657 回答