HTML等同于CSS的样式表是什么?

时间:2019-03-23 20:06:44

标签: html css

我想在所有HTML文档中插入一个导航div。 有没有一种方法可以将整个div放在每个文档中?我认为解决方案类似于CSS样式表。

我不知道在没有Javascript或jQuery 的情况下执行此操作,如果可能的话,我想避免使用它。

<html>
 <body>
  <div>
   //CONTENT//
  <div>
 </body>
</html>

我想将div放在单独的文档中,并放入某种形式的链接,以替换包含div的每个文档中的链接。

1 个答案:

答案 0 :(得分:0)

编辑:我没有注意到您也不想使用JS。 我将把这个答案留给您解决部分问题。

解决方案:

如果您不想使用jQuery之类的ANY库或Angular / React / Vue之类的框架,则可以选择使用Web components(我在下面的链接中添加了说明)。

注意:别忘了检查Browser support

您可以选择HTML templatesCustom elements

让我们以HTML模板为例:

<table id="producttable">
  <thead>
    <tr>
      <td>UPC_Code</td>
      <td>Product_Name</td>
    </tr>
  </thead>
  <tbody>
    <!-- existing data could optionally be included here -->
  </tbody>
</table>

<template id="productrow">
  <tr>
    <td class="record"></td>
    <td></td>
  </tr>
</template>

现在已经创建了表并定义了模板,我们使用JavaScript在表中插入行,并以模板为基础构造每行:

// Test to see if the browser supports the HTML template element by checking
// for the presence of the template element's content attribute.
if ('content' in document.createElement('template')) {

    // Instantiate the table with the existing HTML tbody
    // and the row with the template
    var template = document.querySelector('#productrow');

    // Clone the new row and insert it into the table
    var tbody = document.querySelector("tbody");
    var clone = document.importNode(template.content, true);
    var td = clone.querySelectorAll("td");
    td[0].textContent = "1235646565";
    td[1].textContent = "Stuff";

    tbody.appendChild(clone);

    // Clone the new row and insert it into the table
    var clone2 = document.importNode(template.content, true);
    td = clone2.querySelectorAll("td");
    td[0].textContent = "0384928528";
    td[1].textContent = "Acme Kidney Beans 2";

    tbody.appendChild(clone2);

} else {
  // Find another way to add the rows to the table because 
  // the HTML template element is not supported.
}

什么是Web组件(来自developer.mozilla.org文档)?

作为开发人员,我们都知道尽可能多地重复使用代码是一个好主意。传统上,对于自定义标记结构而言,这并不容易-考虑一下有时需要编写复杂的HTML(以及相关的样式和脚本)来呈现自定义UI控件,以及多次使用它们会使您的页面陷入混乱如果您不小心的话。

Web组件旨在解决此类问题-它由三项主要技术组成,可以一起使用以创建具有封装功能的通用自定义元素,这些元素可以在任何需要的地方重复使用而不必担心代码冲突。

  1. 自定义元素:一组JavaScript API,可让您定义自定义元素及其行为,然后可以根据需要在用户界面中使用它们。
  2. 阴影DOM:一组JavaScript API,用于将封装的“阴影” DOM树附加到元素(与主文档DOM分开呈现)并控制相关功能。 这样,您可以将元素的功能设为私有,这样就可以编写脚本和设置样式,而不必担心会与文档的其他部分发生冲突。
  3. HTML模板:使用<template><slot>元素,您可以编写未在渲染页面中显示的标记模板。然后可以将它们作为自定义元素结构的基础重复使用多次。