【问题标题】:Create and Use a Custom HTML Component?创建和使用自定义 HTML 组件?
【发布时间】:2017-11-21 17:51:39
【问题描述】:

我有以下本地 html:

<html>

<head>
  <link rel="import" href="https://mygithub.github.io/webcomponent/">
</head>

<body>
  <!-- This is the custom html component I attempted to create -->
  <img-slider></img-slider>
</body>

</html>

以及以下对模板的尝试:

<template>
  <style>
      .redColor{
        background-color:red;
      }
  </style>
  <div class = "redColor">The sky is blue</div>
</template>

<script>
  // Grab our template full of slider markup and styles
  var tmpl = document.querySelector('template');

  // Create a prototype for a new element that extends HTMLElement
  var ImgSliderProto = Object.create(HTMLElement.prototype);

  // Setup our Shadow DOM and clone the template
  ImgSliderProto.createdCallback = function() {
    var root = this.createShadowRoot();
    root.appendChild(document.importNode(tmpl.content, true));
  };

  // Register our new element
  var ImgSlider = document.registerElement('img-slider', {
    prototype: ImgSliderProto
  });
</script>

this article 中所述。当我运行代码时,我得到:

未捕获的类型错误:无法读取 null 的属性“内容” 在 HTMLElement.ImgSliderProto.createdCallback ((index):20)

换句话说,document.querySelector('template'); 返回 null。什么给了?

我的目标是创建自定义 html 元素并将其显示在链接模板代码的网站上。我 100% 确定我正确地提取了远程模板代码(显然,因为我在该代码中得到了错误)。

附:我使用的是最新的 Chrome,所以我不需要 polyfill。

【问题讨论】:

标签: javascript html css templates web-component


【解决方案1】:

试试这个:

  var tmpl = (document.currentScript||document._currentScript).ownerDocument.querySelector('template');

您遇到的问题是模板实际上并不是document 的一部分,而是currentScript 的一部分。由于 polyfill 和浏览器的差异,您需要检查 currentScript_currentScript 才能正常工作。

还要注意,HTML 导入永远不会完全跨浏览器。大多数 Web 组件正在转向基于 JavaScript 的代码,并将使用 ES6 模块加载进行加载。

有些东西有助于在 JS 文件中创建模板。使用反引号(`)是一种合理的方式:

var tmpl = document.createElement('template');
tmpl.innerHTML = `<style>
  .redColor{
    background-color:red;
  }
</style>
<div class = "redColor">The sky is blue</div>`;

【讨论】:

  • 谢谢,现在试试,你能解释一下吗?
  • 我的更改是否回答了您的问题?
  • 这解决了我的问题,一旦接受时间缓冲区用完,我会回来接受。谢谢。
猜你喜欢
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-10
  • 2021-12-28
  • 2011-03-06
相关资源
最近更新 更多