get属性Value() 在检索自定义 CSS 属性 值时包含 CSS 格式的空格

getPropertyValue() includes whitespace of CSS formating when retrieving Custom CSS Property Values

当我获得自定义 CSS 属性 的值时,getPropertyValue 方法 returns 一个包含我在 [=17= 中使用的空格的 DOMString ].我应该使用另一种方法来获取自定义 CSS 属性的值(之后不需要修整的方法)吗?

function getCustomPropertyValue(element,customPropertyName)
{
    let style = window.getComputedStyle(element);
    return style.getPropertyValue(customPropertyName);
}
let value = getCustomPropertyValue(document.body,"--color1");
console.log(`'${value}'`);
body { --color1: #333333; }

请注意,当您 运行 代码片段时,getPropertyValue 函数 returns 一个具有前导空格的值(这是我的 CSS 格式的产物).

当您以正确的方式使用 CSS 变量时,它会起作用。您可以找到更多详细信息 here.

function getCustomPropertyValue(element, customPropertyName) {
  let style = window.getComputedStyle(element);
  return style.getPropertyValue(customPropertyName);
}
let value = getCustomPropertyValue(document.body, "--color1");
console.log(`'${value}'`);
:root {
  --color1:#333333;
}

body {
  color: var(--color1);
}

只需删除 CSS 中的白色-space。

body { 
--color1:#333333; 
}

这是一个经过深思熟虑的决定,允许自定义 CSS 属性认为空格很重要。所以修剪是要走的路。

我听说用定义的语法注册 属性 可能会改变这一点,但我认为这还不是标准,我自己也没有尝试过。