你能在 html 中创建可重用的组件吗?假设我想将一些 css/html 和 js 封装到一个整洁的可重用组件中。 Web 开发人员如何做到这一点?我来自地球的 Flex、C# 一侧。
最佳答案
2017年更新
这个问题已有 7 年历史,此后发生了很多变化。 Web components现在已经在每个主流浏览器中实现或可以与 polyfills 一起使用。这意味着您可以使用 Polymer通过谷歌或 X-Tag由微软支持,正是为此而生。
使用 Polymer 的示例方法:
custom-tag.html 中的自定义标签声明:
<dom-module id="custom-tag">
<template>
<style>
h1 {
color: red;
}
</style>
<div class="text-holder">
<h1>[[name]]</h1>
<p>[[description]]</p>
</div>
</template>
</dom-module>
<script>
Polymer({
is: "custom-tag",
properties: {
name: String,
description: String
}
});
</script>
如何在页面中使用自定义标签:
在头部包含标签:
<link rel="import" href="path/to/custom-tag.html"/>
然后:
<custom-tag
name="Lorem"
description="Lorem ipsum dolor sit amet.">
</custom-tag>
由于 html 导入,您将需要一个简单的 http 服务器。您谈到的封装由 Shadow DOM 支持——封装在自定义标记内的 javascript 和 css 不会“流出”并更改元素外部的任何内容,反之亦然(除非您强制执行)。 Polymer 出来了相当大的元素 Assets ,你可以找到它here .
涵盖了有关使用元素和创建您自己的元素的所有内容 here .
关于html - HTML 中的可重用 View 组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2747340/