使用 Object.setPrototype() 修补同一文档中的混合 HTML 和 XML 元素

时间:2021-06-03 03:32:25

标签: javascript html xml browser element

假设我将一个元素从 XMLDocument 移动到 HTMLDocument

// create XML doc
const xmlDoc = document.implementation.createDocument(null, 'my-root');

// reference the XML element
const myRoot = xmlDoc.childNodes[0];

// move to this HTML doc
document.body.appendChild(myRoot);

myRoot instanceof Element;     // true
myRoot instanceof HTMLElement; // false

myRoot.setAttribute('style', '...'); // doesn't render styles

// try to patch it
Object.getPrototypeOf(myRoot); // Element
Object.setPrototypeOf(myRoot, HTMLUnknownElement.prototype);
Object.getPrototypeOf(myRoot); // HTMLUnknownElement

myRoot.style;                        // error, illegal invocation
myRoot.setAttribute('style', '...'); // still doesn't render styles

由于 myRoot 是一个 Node,所以它参与 DOM 树可以被查询等。它还具有来自 Element 的所有与属性相关的功能。

但是:

  • 它缺少 HTMLElement 中所有与样式相关的功能
  • 无法升级为自定义元素
  • 在序列化/反序列化回合之后,它将成为 HTMLUnknownElement
  • setPrototypeOf 起初似乎有效,但 style 属性失败
  • 即使在设置原型之后,也不会呈现任何 style 属性更改

为什么在设置原型后访问 style 会中断? 为什么设置原型后样式不起作用?

0 个答案:

没有答案
相关问题