css-selectors - 是否有派生 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 类
需要一些字符串处理,因为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>
推荐阅读
- php - 工会中的Laravel关系冲突
- javascript - Highcharts 多个饼图系列悬停
- python - 如何从使用 Python 的文件中以十六进制字符串值存在的标头中提取 IPv6 字段属性值?
- vue.js - 如何阻止 vue eslint 规则更改?
- typescript - TypeScript - 编译为单个文件
- html - 有没有办法在 Jinja2 中执行多个“阅读更多”按钮?如果没有,怎么办
- sql - 计算选择查询中的开始和结束时间
- javascript - isVisible 在使用 jest-dom 的 Jest 测试中不起作用
- javascript - 如何重新请求浏览器麦克风的权限?
- docker - 如何使用 ADD 将测试添加到“集成”目录中?