使用 Bootstrap 和模板标签

Using Bootstrap With The Template Tag

我一直在学习 Web 组件的原始版本,但 运行 遇到了麻烦。当尝试在模板标签内使用来自 bootstrap 的网格时,特别是容器 class,它不会对其应用任何 bootstrap 样式。

//Template File
<template>

  <top-bar>
    <div class="container">
      <h1>Hello World</h1>
    </div>
  </top-bar>

</template>

<script>
  var el = document.querySelectorAll('top-bar');
  if(el != null) {
    //Custom Elements
    document.registerElement('top-bar');
    //Import Elements
    for(var i = 0; i < el.length; i++) {
      var shadow = el[i].createShadowRoot();
      var template = document.querySelector('#topbar').import.querySelector('template');
      var clone = document.importNode(template.content, true);
      shadow.appendChild(clone);
    }
  }
</script>

常规 Bootstrap 样式(字体、样式重置等)应用正确,未出现控制台错误。

//Index File
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Web Components</title>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
  <link rel="import" href="topbar.html" id="topbar">
</head>
<body>

  <top-bar></top-bar>

</body>
<script src="http://code.jquery.com/jquery-2.1.4.min.js">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
</html>

我试图将 link 和 bootstrap 的脚本文件放入模板文件中(但在模板标签之外,因为 link 标签将不会在模板标签)。 Bootstrap 将加载,就像我在索引页面上调用它一样,但容器仍然不会从 Bootstrap.

继承任何样式

非常感谢您提供的任何帮助!

阴影 DOM 停止 CSS 传播。 如果您想要自然 CSS 传播,请不要使用 Shadow DOM。

var shadow = el[i] //.createShadowRoot();  //will work

PS:

1°) 你对 <template> 的使用是错误的:不要嵌套 <top-bar> 标签。

2°) 你对 registerElement 的使用毫无意义。为您的新元素提供原型。

没有阴影 DOM 的自定义元素和模板 topbar.html 的正确实现是:

<template>
    <div class="container">
        <h1>Hello World</h1>
    </div>
</template>

<script>

//Import Elements
var template = document.querySelector('#topbar').import.querySelector('template');

//Custom Elements
var topBar = Object.create( HTMLElement.prototype )

topBar.createdCallback = function ()
{
    var shadow = this //.createShadowRoot()
    var clone = document.importNode( template.content, true );
    shadow.appendChild( clone );
}

document.registerElement( 'top-bar', { prototype: topBar } );

</script>

请注意我在 2019 年 3 月 1 日收到的这条消息 google Chrome:

[弃用] document.registerElement 已弃用,将于 2019 年 3 月左右在 M73 中删除。请改用 window.customElements.define。有关详细信息,请参阅 https://www.chromestatus.com/features/4642138092470272

所以现在,insteadOf : document.registerElement( 'approve-btn', { 原型: myCustomElement } );

...现在看来我们需要做的是:

customElements.define("approve-btn", myCustomElement);

mycustomElement 应该是这样的类:

class ApproveBtn extends HTMLElement {
  constructor() {
    // Always call parent constructor first
    super();

    // Get template content from DOM
    this.template = document.getElementById("approve-btn");
    this.templateContent = this.template.content;

    this.appendChild(this.templateContent);


  }
 }

然后最后执行:

customElements.define("approve-btn", ApproveBtn);