【问题标题】:Using web fonts with Polymer custom elements将 Web 字体与 Polymer 自定义元素一起使用
【发布时间】:2018-11-12 09:24:32
【问题描述】:

我在将 Typekit 字体加载到 Polymer 组件时遇到问题。

我最初在my-element.js

import {html, PolymerElement} from "../node_modules/@polymer/polymer/polymer-element.js";

export class MyElement extends PolymerElement {
  static get template() {
    return html`
      <style>
        @import url(https://use.typekit.net/mykit.css)
        .my-class { font-family: "typekit-font-family"; }
      </style>

      <div class$="my-class">
        <slot/>
      </div>
    `;
  }
}

window.customElements.define("my-element", MyElement);

我了解到 @import url() 不是一个好方法,所以我用 polymerelements/paper-styles 导入 Roboto 的方式替换了它:

typekit-loader.js:

// Based on https://github.com/PolymerElements/font-roboto/blob/master/roboto.js
// and https://github.com/PolymerElements/paper-styles

export {}; // ensure this file can only be parsed as a module.

// Give the user the choice to opt out of font loading.
if (!window.polymerSkipLoadingFontRoboto) {
  const link = document.createElement("link");
  link.rel = "stylesheet";
  link.type = "text/css";
  link.crossOrigin = "anonymous";
  link.href = "https://use.typekit.net/mykit.css";
  document.head.appendChild(link);
}

my-element.js:

import {html, PolymerElement} from "../node_modules/@polymer/polymer/polymer-element.js";
import "./typekit-loader.js";


export class MyElement extends PolymerElement {
  static get template() {
    return html`
      <style>
        .my-class { font-family: "typekit-font-family"; }
      </style>

      <div class$="my-class">
        <slot/>
      </div>
    `;
  }
}

window.customElements.define("my-element", MyElement);

typekit-loader.js 本质上最终所做的是将&lt;link rel="stylesheet" /&gt; 标记添加到链接到并使用my-element.js 的文档的&lt;head&gt;。这似乎有效,因为我可以看到正在使用我的 typekit 字体。

但我的问题是它为什么有效? Shadow DOM 不应该有权访问主机页面自己的样式,那么我的 div 是如何获得自定义字体的呢?链接到 Web 字体与链接到文档的 &lt;head&gt; 中的任何随机 css 文件有何不同?如果我在主文档中添加了一条样式规则,说明.my-class 应该是红色的,那么它不适用。

【问题讨论】:

    标签: polymer shadow-dom custom-element typekit


    【解决方案1】:

    Shadow DOM 将仅隔离用户定义的 CSS 样式。

    默认 CSS 样式 - 应用于每个新文档的 CSS 样式 - 将应用样式。例如:背景、文字颜色、内边距……

    默认 CSS background-colorinherit。因此,如果您将其全局定义为 blue,那么即使在 Shadow DOM 中,它也会显示为 blue

    字体也一样:全局定义或加载的字体在Shadow DOM中继承,可以在其中显示。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-21
      • 1970-01-01
      • 2019-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多