我有一个简单的类,它接收一个元素,找到它的 RGB 颜色,然后将它转换为 HEX。这有效但是当我将它添加到元素时它不起作用像这样:
import * as colorConvert from "color-convert"; // a package to convert RGB to hex
export default class Darken {
constructor(element) {
this.element = element;
}
hex() {
const rgb = window.getComputedStyle(this.element).color;
const exp = /\(([^)]+)\)/;
const matches = exp.exec(rgb);
const rgbCode = matches[1];
const [r, g, b] = rgbCode.split(", ");
return colorConvert.rgb.hex(r, g, b);
}
changeTheStylesheet() {
const newColor = `#${this.hex()}`; // This gives me the hex code that I want #010300
console.log(newColor); // It's as I want it in the console
this.element.style.color = newColor; // But here it gets shown in RGB rgb(1, 3, 0)
}
}
我想使用十六进制代码而不是 RGB。 谢谢。
最佳答案
这是因为 style 属性只能返回 RGB 格式的颜色代码。
关于javascript - 如何使用 JS 将十六进制代码添加到 HTML 元素(内联样式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59008450/