在本文中,作者建议在设计语法高亮 Web 组件时使用
data-
属性。
给出的理由是:
Technically speaking, the browser would let us write the attributes like this:
<code-tab language="HTML" escaped="true" line-numbers="true">
But if any of those attribute names ever become web standard, that could cause issues. Data attributes protect us from that, as they're developer defined.
这是正确的吗?
属性本身可以成为网络标准吗?我假设它们的含义基于上下文,因此
language
上下文中的 code-tab
之类的属性将被视为该上下文中唯一的?
是的,这是完全正确的,例如,最近 HTML 标准确实向所有元素添加了
popover
属性。如果您的自定义元素使用该属性,那么现在将使用默认的 display: none
规则进行渲染:
if (!("popover" in HTMLElement.prototype)) {
console.warn("This browser doesn't support the popover attribute");
}
<my-elem>Some content</my-elem>
<my-elem popover>Hey!?</my-elem>
更好地使用
data-attribute
,或者已经在其他元素上定义的属性,因此不会将其作为全局属性,因为会发生冲突。