html - HTML 中的可重用 View 组件

标签 html components code-reuse

你能在 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/

相关文章:

php - mysql数据库连接错误

jquery - 表列被 scollbars 压扁

javascript - Material-UI 组件样式定制 - 将选择组件的颜色更改为白色

git - 使用 GIT 升级修改后的模块

javascript - Jquery css显示div?

javascript - 必须在 jQuery 上单击两次

java - 有没有办法重用<c :url> logic inside my custom JSP tag?

xcode - 在 Swift 中,用于设计控制台应用程序的代码重用选项是什么,我该如何实现它们?

angular - 如何在 Angular 9 中创建自定义文本框组件

.net - COM+ 组件由 C# 中的 Windows 服务托管,用于控制外部设备