将导入的样式表应用于自定义元素的模板标签内容

将导入的样式表应用于自定义元素的模板标签内容

本文介绍了如何将导入的样式表应用于自定义元素的模板标签内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我尝试使用的代码

<script type="text/javascript" src="dropzone.js"></script><link href="dropzone.css" rel="stylesheet"/><模板 id="dropzoneTemplate"><div id="dZUpload" class="dropzone"><div class="dz-default dz-message"></div>

<dropzone></dropzone><脚本>var DropzoneElementPrototype = Object.create(HTMLElement.prototype);DropzoneElementPrototype.createdCallback = function () {var t = document.querySelector('#uploadImageTemplate');var clone = document.importNode(t.content, true);this.createShadowRoot().appendChild(clone);};var DropzoneElement = document.registerElement('dropzone', {原型:DropzoneElementPrototype});</script>

但是导入的样式表 dropzone.css 没有应用到template 标签内的内容,即class dropzone 未从 dropzone.css 获取其样式,因此导入文件中的样式未应用于 template 标记内的 div 等元素.

我也尝试将这个链接标签放在模板标签中,但这也不起作用.

是否可以将导入的样式表应用于自定义元素的模板标签内容?

解决方案

元素中使用 @import css 样式规则:

<风格>@import url('dropzone.css')</风格><div id="dZUpload" class="dropzone"><div class="dz-default dz-message"></div>

注意:

  • 根据 CSS2 规范@import 规则必须在除 @charset 之外的任何其他规则之前.

  • 如果您的样式表定义了 @font-face,它也必须包含在主文档中.

Here is the code I am trying to use

<script type="text/javascript" src="dropzone.js"></script>
<link href="dropzone.css" rel="stylesheet"/>

<template id="dropzoneTemplate">
	<div id="dZUpload" class="dropzone">
		  <div class="dz-default dz-message"></div>
	</div>
</template>
<dropzone></dropzone>

<script>
    var DropzoneElementPrototype = Object.create(HTMLElement.prototype);

    DropzoneElementPrototype.createdCallback = function () {
        var t = document.querySelector('#uploadImageTemplate');
        var clone = document.importNode(t.content, true);
        this.createShadowRoot().appendChild(clone);
    };

    var DropzoneElement = document.registerElement('dropzone', {
        prototype: DropzoneElementPrototype
    });

</script>

But the imported stylesheet dropzone.css is not getting applied to the content inside template tag, i.e. class dropzone is not getting its styles from dropzone.css so the styles in the imported file is not getting applied to elements like div inside template tag.

I have also tried to put this link tag inside the template tag, but that doesn't work either.

Is it possible to apply imported stylesheet to template tag content for a custom element?

解决方案

Use an @import css style rule inside your <template> element:

<template id="dropzoneTemplate">
    <style>
       @import url( 'dropzone.css' )
    </style>
    <div id="dZUpload" class="dropzone">
          <div class="dz-default dz-message"></div>
    </div>
</template>

Note:

  • According to the CSS2 specification, @import rule must precede any other rules except @charset.

  • If your stylesheet defines a @font-face, it must be included in the main document too.

这篇关于如何将导入的样式表应用于自定义元素的模板标签内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 00:06