首页 > 解决方案 > A-Frame appendChild 适用于 Firefox 但不适用于 Chrome

问题描述

我正在尝试使用模板元素在 A-Frame 中动态创建新实体。辅助函数如下所示:

function htmlToElement(html) {
    const template = document.createElement('template');

    // Never return a text node of whitespace as the result.
    html = html.trim();

    template.innerHTML = html;
    return template.content.firstChild;
}

我像这样使用它:

document.querySelector('a-scene').addEventListener('loaded', () => {
  const cube = htmlToElement('<a-box position="0 1 -2"></a-box>')

  document.querySelector('a-scene').appendChild(cube);
});

这在 Firefox 中效果很好,但在 Chrome 中,实体不会出现。如果查看document.querySelector('a-box')没有object3D属性的实体,那么我不认为将元素附加到场景中是在 Chrome 上使用 A-Frame 注册元素。为了让它在 Chrome 中工作,我缺少什么?这是一支

谢谢!

标签: javascriptaframe

解决方案


innerHMTL 的模板行为可能会有所不同。您可以使用createContextualFragment. 要为 A-Frame 转储原始 HTML,请执行以下操作:

el.appendChild(document.createRange().createContextualFragment(str));


推荐阅读