首页 > 解决方案 > 是否有派生 HTML 自定义元素的 CSS 选择器?

问题描述

假设有一个以典型方式定义的自定义 HTML 元素,另一个继承自它:

class CEParent extends HTMLElement { constructor() { super(); } }
class CEChild  extends CEParent    { constructor() { super(); } }
customElements.define("ce-parent", CEParent);
customElements.define("ce-child",  CEChild);

现在假设 HTML 只包含对<ce-child></ce-child>元素的引用。是否可以选择/<ce-child>风格ce-parent

喜欢

ce-parent:and-derived-too {
    ...
}

?

标签: css-selectorscustom-element

解决方案


这会将父元素名称分配为每个元素上的 CSS 类

需要一些字符串处理,因为constructor.name匿名函数是“”(空字符串)

所以 DOM 中的 Bono (U2) 是:

<style>
  body       {font-size:1.2em            }
  .Homininae {background: lightgreen; display:block;clear:both  }
  .Hominini  {background:green;        }
  .Homo      {color: gold;             }
  *:after { content:attr(class); float:right}
</style>
<script>
  class Homininae extends HTMLElement {
    connectedCallback() {
      function proto(ref, chain = '', str = ref.toString()) {
        if (str.slice(0, 5) === "class")
          return proto(ref.__proto__, chain + " " + str.match(/class (\w*)/)[1]);
        else return chain;
      }
      let classes = proto(this.constructor.__proto__);
      this.className = classes;
      this.innerHTML = `<b>${this.innerHTML}</b> (${this.nodeName}) `;
    }
  }
  class Gorillini extends Homininae {};
  class Hominini  extends Homininae {};
  class Pan       extends Hominini {};
  class Homo      extends Hominini {};
  customElements.define('a-human'     , class extends Homo {});
  customElements.define('a-bonobo'    , class extends Pan {});
  customElements.define('a-chimpanzee', class extends Pan {});
  customElements.define('a-gorilla'   , class extends Gorillini {});
</script>

<a-human>Bono</a-human>
<a-bonobo>Kanzi</a-bonobo>
<a-chimpanzee>Ham the Astrochimp</a-chimpanzee>
<a-chimpanzee>Bonzo</a-chimpanzee>
<a-gorilla>Koko</a-gorilla>


推荐阅读