代码之家  ›  专栏  ›  技术社区  ›  nonopolarity

为什么?窗口.getComputedStyle()返回属性名为“backgroundColor”的对象,但使用属性名“backgroundColor”也可以吗?

  •  -1
  • nonopolarity  · 技术社区  · 6 年前

    至少在Chrome和Firefox中是这样:

    Object.keys(getComputedStyle(document.body)).includes("backgroundColor")  // => true
    Object.keys(getComputedStyle(document.body)).includes("background-color") // => false
    

    getComputedStyle(document.body)["background-color"]    // "rgb(255, 255, 255)"
    getComputedStyle(document.body)["backgroundColor"]     // "rgb(255, 255, 255)"
    

    所以如果 background-color 不是钥匙,怎么可能

    getComputedStyle(document.body)["background-color"]
    

    展示什么?我知道在jQuery中, fontSize 与相同 font-size

    1 回复  |  直到 6 年前
        1
  •  1
  •   Ry-    6 年前

    单凭这种行为是不需要魔法的: Object.keys 只返回自己的、可枚举的、字符串命名的属性。任何JS对象都可以通过 "background-color" 要么是

    1. 在原型链上更高,或者
    2. 不可枚举。

    前者适用于 “背景色” 在当前的Firefox上,计算样式的原型上有一个getter/setter对:

    console.log("background-color" in getComputedStyle(document.body));
    console.log(
        Object.getOwnPropertyDescriptor(CSS2Properties.prototype, "background-color"));

    Chrome似乎使用了magic,其中连字符别名是不可枚举的可枚举属性。

    for (let prop in document.body.style) {
      if (prop === "background-color") {
        console.log("found it");
      }
    }
    
    console.log(Object.getOwnPropertyDescriptor(document.body.style, "background-color"));

    但是,非宿主对象代理仍然可以这样做。

    const magic = new Proxy({
      "background-color": "red",
    }, {
      ownKeys(target) {
        return [];
      },
    });
    
    console.log(Object.keys(magic));
    console.log(Object.getOwnPropertyDescriptor(magic, "background-color"));